Undistraction
Undistraction

Reputation: 43579

Saving Model Causes Failed Invalidation in has_many / belongs_to Relationship

I have two models:

class Customer < ActiveRecord::Base

   has_many :orders

end

class Order < ActiveRecord::Base

   belongs_to :customer
   validates :customer, presence: true

end

I get a validation error if I do the following:

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

Why does this cause the following validation error:

Validation failed: Order is invalid

If I instead save the customer:

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

I get the error:

Validation failed: Customer can't be blank

What is going on? Should I not be validation an belongs_to relationship?

Upvotes: 1

Views: 341

Answers (1)

jvnill
jvnill

Reputation: 29599

To get around this issue, use inverse_of on both end of the association.

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

Then you should be able to do the following

>> customer = Customer.new
>> customer.orders << Order.new
>> customer.save! # should create both customer and order

Upvotes: 3

Related Questions