Current year in Ruby on Rails -
how can current year in ruby on rails?
i tried variety of things, including
- date.current.year
- time.now.year
the problem return previous year in cases year changes after launching server (eg. after new year's).
relevant code:
model brewery.rb
class brewery < activerecord: :base ... validates :year, numericality: { only_integer: true, less_than_or_equal_to: date.today.year } ...
problem occurs when creating new brewery, assumed date.today.year evaluated whenever action takes place.
in example date.today.year
evaluated once, when class loaded , doesn't change anymore.
when use lambda in validator declaration, re-evaluates block each time when validates attribute:
validates :year, numericality: { only_integer: true, less_than_or_equal_to: ->(_brewery){ date.current.year } }
furthermore suggest use date.current
instead of date.today
, because current
pays attention time zone settings.
Comments
Post a Comment