0

我有两个模型 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

如何正确验证相关文件的数量?

4

1 回答 1

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
于 2013-03-30T15:07:27.730 回答