rails中两个模型之间的多个关联

时间:2010-12-03 21:50:40

标签: ruby-on-rails associations

我正试图在Rails 3应用程序中以两种方式关联两个模型。人们有很多宠物,每个人都可以养一只宠物。

我使用正确的关联和外键吗?

当我做person.favorite_pet_id和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

1 个答案:

答案 0 :(得分:4)

因为看起来你在个人表中有了favorite_pet_id(你应该这样),你需要使用“belongs_to”关联而不是“has_one”,如下所示:

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

这应该可以解决您的问题。我希望这有帮助!