validates_inclusion_of no longer working the same in Rails 4.1?

一曲冷凌霜 提交于 2019-11-29 14:31:51

问题


The following code made sure that a time_zone chose is within the time zones in ActiveSupport::TimeZone.us_zones:

validates_inclusion_of :time_zone, in: ActiveSupport::TimeZone.zones_map(&:name)

Worked great in Rails 4.0. Just upgraded to Rails 4.1 and I'm getting this error on my index page (so just simply viewing the models):

An object with the method #include? or a proc, lambda or symbol is required, and must be supplied as the :in (or :within) option of the configuration hash

I'm guessing from that, ActiveSupport::TimeZone.zones_map(&:name) is no longer a valid value for the in property?


回答1:


try adding .keys ?

validates :time_zone, 
  inclusion: { 
    in: ActiveSupport::TimeZone.zones_map.keys 
  } 



回答2:


In Rails 5, ActiveSupport::TimeZone.zones_map is a private method. Therefore, if you want your validation to work, I suggest the following syntax:

validates :time_zone, inclusion: { in: ActiveSupport::TimeZone.all.map(&:name) }



回答3:


If you want to keep using validates_inclusion_of this works as well:

validates_inclusion_of :time_zone, 
   :in => ActiveSupport::TimeZone.zones_map(&:name).keys, 
   :message => "is not a valid time zone"


来源:https://stackoverflow.com/questions/22950540/validates-inclusion-of-no-longer-working-the-same-in-rails-4-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!