rails validation: :allow_nil and :inclusion both needed at the same time

馋奶兔 提交于 2019-12-06 16:29:56

问题


Usually the field 'kind' should be allowed blank. but if it is not blank, the value should included in ['a', 'b']

validates_inclusion_of :kind, :in => ['a', 'b'], :allow_nil => true

The code does not work?


回答1:


This syntax will perform inclusion validation while allowing nils:

validates :kind, :inclusion => { :in => ['a', 'b'] }, :allow_nil => true



回答2:


In Rails 5 you can use allow_blank: true outside or inside inclusion block:

validates :kind, inclusion: { in: ['a', 'b'], allow_blank: true }

or

validates :kind, inclusion: { in: ['a', 'b'] }, allow_blank: true

tip: you can use in: %w(a b) for text values




回答3:


check also :allow_blank => true




回答4:


If you are trying to achieve this in Rails 5 in a belongs_to association, consider that the default behaviour requires the value to exist.

To opt out from this behaviour you must specify the optional flag:

belongs_to :foo, optional: true 

validates :foo, inclusion: { in: ['foo', 'bar'], allow_blank: true } 



回答5:


In Rails 5.x you need, in addition to the following line, to call a before_validation method:

validates_inclusion_of :kind, :in => ['a', 'b'], :allow_nil => true

The before_validation is needed to convert the submitted blank value to nil, otherwise '' is not considered nil, like this:

  before_validation(on: [:create, :update]) do
    self.kind = nil if self.kind == ''
  end

For database disk space usage it is of course better to store nil's than storing empty values as empty strings.



来源:https://stackoverflow.com/questions/17359853/rails-validation-allow-nil-and-inclusion-both-needed-at-the-same-time

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