我有两种模式:
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
关系吗?
答案 0 :(得分:2)
要解决此问题,请在关联的两端使用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