开发者

How to use MongoID validates_inclusion_of

I 开发者_开发知识库have a model with a field that can contain a list of values. I want that list to be limited to a subset. I want to use validates_inclusion_of, but probably misunderstand that validation.

class Profile
  include Mongoid::Document
  field :foo,   :type => Array

  validates_inclusion_of :foo, in: %w[foo bar]
end

p = Profile.new
p.valid?   #=> false; this is correct, as it should fail on empty lists.
p.foo = ["bar"]
p.valid?   #=> false; this is incorrect. I would expect it to pass now.
p.errors   #=> {:foo=>["is not included in the list"]}

What am I doing wrong? Can validates_inclusion_of be used for arrays?


Your field value is an array (field :foo, :type => Array) Validation expects field to be not an array to check its inclusion. By your example validation is checking for ['foo', 'bar'].include?(['bar']) # => false

So correct your :in option in validates_inclusion_of:

validates_inclusion_of :foo, in: [['foo'], ['bar']]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜