Rails 你们遇到过 validates_associated 会给出重复的 errors 信息的吗?

hegwin · July 31, 2013 · Last by zlx_star replied at July 31, 2013 · 3189 hits

大概故事是这样……

class Company < AR::Base
  has_many :brands
  validates_associated :brands
end

class Brand < AR::Base
  belongs_to :company
  validates_presence_of :name
end

然后前台更新 Company 的时候,如果添加一个 brand 但是不填名字,会给出两条出错的信息。

  • Brands is invalid
  • Brands is invalid

BTW,如果添加两个 brand 且不填名字。会给出 3 条……

我进 rails console 之后去试验,也会有同样的问题

c = Company.find(1)
c.valid?
  => true
c.brands.new
  => #<Brand id: nil, custom: 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"]

借问一下,添加 validates_associated 有什么好处?

You need to Sign in before reply, if you don't have an account, please Sign up first.