Niels Kristian
Niels Kristian

Reputation: 8865

Validate presence of associated model

I don't get it I have the following models:

class Seller < ActiveRecord::Base
  has_many :cars, :dependent => :destroy
end

class Car < ActiveRecord::Base
  belongs_to :seller
  # I have tried both with the validates existence gem:
  validates :existence => {:allow_nil => false}
  # And normally...
  validates_presence_of :seller
end

But nothing works if I do the following:

seller = Seller.new()
seller.cars.build()
seller.save # I get => false @messages={:seller=>["does not exist"], :seller_id=>["does not exist"]}  

I should be able to do this right?

It's like - it's validating the associated model before the mother-object has been saved - and i have NOT defined a validates_associated or something like that.

Any clue? Or am I getting the order of saving and validating all wrong?

Upvotes: 0

Views: 448

Answers (2)

andrewpthorp
andrewpthorp

Reputation: 5106

I have run into this in the past, and have used "inverse_of" to solve it. You also need "accepts_nested_attributes_for". So in the seller, you would want to change your code to the following:

class Seller < ActiveRecord::Base
  has_many :cars, :dependent => :destroy, :inverse_of => :seller
  accepts_nested_attributes_for :cars
end

Upvotes: 1

Marek Př&#237;hoda
Marek Př&#237;hoda

Reputation: 11198

Seller does not exist because it has not been saved in the database, it's just in the memory, and so Car does not know Seller's id which it needs to know - it has to add it to the seller_id column. So you first have to save Seller and you don't need the validates_presence_of :seller call in Car.

Upvotes: 1

Related Questions