Nathan Manousos
Nathan Manousos

Reputation: 13858

multiple associations between two models in rails

I'm trying to associate two models in two ways in a Rails 3 app. People have many pets and each person can have one favorite pet.

Am I using the correct associations and foreign keys?

I actually get two different numbers when I do person.favorite_pet_id and person.favorite_pet.id

class Person < ActiveRecord::Base
  has_many :pets # pets table has a person_id
  has_one :favorite_pet, :class_name => 'Pet' # persons table has favorite_pet_id 
end


class Pet < ActiveRecord::Base
  belongs_to :person # using person_id in pets table
end

Upvotes: 3

Views: 825

Answers (1)

Jaime Bellmyer
Jaime Bellmyer

Reputation: 23317

Since it looks like you have the favorite_pet_id in the persons table (as you should) you need to use the "belongs_to" association instead of "has_one", like so:

class Person < ActiveRecord::Base
  has_many :pets # pets table has a person_id
  belongs_to :favorite_pet, :class_name => 'Pet' # persons table has favorite_pet_id 
end


class Pet < ActiveRecord::Base
  belongs_to :person # using person_id in pets table
end

This should fix your issue. I hope this helps!

Upvotes: 4

Related Questions