【问题标题】:Saving Model Causes Failed Invalidation in has_many / belongs_to Relationship保存模型导致 has_many / belongs_to 关系失效失败
【发布时间】: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


【解决方案1】:

要解决此问题,请在关联的两端使用 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

【讨论】:

  • 有人知道这在 Rails 4.1.8 中是否仍然正确吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多