Multiple associations between two models on rails

I am trying to link the two models in two ways in the Rails 3 application. People have many pets, and each can have one favorite pet.

Am I using the correct associations and foreign keys?

I really 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
+3
source share
1 answer

Since it looks like you have a favorite_pet_id file in the faces table (as it should be), you need to use the membership association, not the has_one association, for example:

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 problem. Hope this helps!

+4
source

Source: https://habr.com/ru/post/1778407/


All Articles