【发布时间】:2013-08-22 15:13:16
【问题描述】:
我有两个模型:
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 关系吗?
【问题讨论】:
-
您需要先保存订单才能保存客户
-
@MrYoshiji 但正如我在问题中所说,保存订单会导致失效错误:“验证失败:订单无效”,因为此时订单的客户关联为零。
标签: ruby-on-rails ruby-on-rails-3 validation activerecord model