这里有两个类,1:n 关系
class Company < AR::Base
has_many :brands
validates_associated :brands
end
class Brand < AR::Base
belongs_to :company
validates_presence_of :name
end
我尝试为公司添加品牌。如果品牌名称为空,它会给我重复的错误消息。
c = Company.find(1)
c.valid?
# => true
c.brands.new
# => #<Brand id: nil, name: nil, company_id: 1, created_at: nil, updated_at: nil>
c.valid?
#=> false
c.errors.full_message
#=> ["Brands is invalid", "Brands is invalid"]
c.brands.last.errors.full_message
#=> ["Name required"]