Att*_*nen 1 ruby ruby-on-rails date
如何在Ruby on Rails中获得当前年份?
我尝试过各种各样的东西,包括
问题是,如果在启动服务器之后年份发生变化(例如新年之后),它们会返回前一年.
相关代码:
型号brewery.rb
class Brewery < ActiveRecord: :Base
...
validates :year, numericality: { only_integer: true, less_than_or_equal_to: Date.today.year }
...
Run Code Online (Sandbox Code Playgroud)
创建新啤酒厂时会出现问题,因此我假设每当该操作发生时都会评估Date.today.year.
spi*_*ann 12
在您的示例中Date.today.year仅评估一次 - 当加载类时,因此不再更改.
在验证程序声明中使用lambda时,每次运行该属性的验证时,它都会重新计算该块:
validates :year, numericality: {
only_integer: true,
less_than_or_equal_to: ->(_brewery) { Date.current.year }
}
Run Code Online (Sandbox Code Playgroud)
此外,我建议使用Date.current而不是Date.today,因为该current方法注重时区设置.