我有两个模型Item和Tag
class Item
include Mongoid::Document
field :title, type: String
has_many :tags
validates_length_of :tags, minimum: 1
end
class Tag
include Mongoid::Document
field :title, type: String
belongs_to :item
end
项目必须至少有1个标签。 创建项目时,验证效果非常好:
item = Item.create(title: "black hole")
item.tags << Tag.create(title: "black")
item.tags << Tag.create(title: "heavy")
puts item.valid? # => true
item.save
但是当修改现有项目时验证失败:
item = Item.find(item.id)
item.title = "nothing"
puts item.tags.count # => 2, it's ok
puts item.valid? # => false, it's wrong
如何正确验证相关文件的数量?
答案 0 :(得分:0)
您是否尝试将attr_accessible
添加到标题?
看起来像这样:
class Item
include Mongoid::Document
attr_accessible :title # <-- here
field :title, type: String
has_many :tags
validates_length_of :tags, minimum: 1
end