1

我有两个模型:

class Customer < ActiveRecord::Base

   has_many :orders

end

class Order < ActiveRecord::Base

   belongs_to :customer
   validates :customer, presence: true

end

如果我执行以下操作,我会收到验证错误:

$ customer = Customer.new()
$ order = Order.new()
$ customer.orders << order
$ order.save!

为什么这会导致以下验证错误:

验证失败:订单无效

如果我改为保存客户:

$ customer = Customer.new()
$ order = Order.new()
$ customer.orders << order
$ customer.save!

我得到错误:

验证失败:客户不能为空

到底是怎么回事?我不应该验证belongs_to关系吗?

4

1 回答 1

3

要解决此问题,inverse_of请在关联的两端使用。

class Customer < ActiveRecord::Base
  has_many :orders, inverse_of: :customer
end

class Order < ActiveRecord::Base
  belongs_to :customer, inverse_of: :orders

  validates :customer, presence: true
end

那么您应该能够执行以下操作

>> customer = Customer.new
>> customer.orders << Order.new
>> customer.save! # should create both customer and order
于 2013-08-22T15:27:36.100 回答