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

Ruby on rails rails中两个模型之间的多个关联,ruby-on-rails,associations,Ruby On Rails,Associations,我试图在Rails 3应用程序中以两种方式关联两个模型。人们有很多宠物,每个人可以有一个最喜欢的宠物 我是否使用了正确的关联和外键 实际上,我在做person.favorite\u pet\u id和person.favorite\u pet.id时会得到两个不同的数字 class Person < ActiveRecord::Base has_many :pets # pets table has a person_id has_one :favorite_pet, :class

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

我是否使用了正确的关联和外键

实际上,我在做person.favorite\u pet\u id和person.favorite\u 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
class-Person'pet'#persons表具有favorite_pet_id
结束
类Pet
由于您在persons表中似乎有最喜爱的宠物id(您应该这样做),因此您需要使用“属于”关联,而不是“有一个”,如下所示:

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
class-Person'pet'#persons表具有favorite_pet_id
结束
类Pet

这将解决您的问题。我希望这有帮助

谢谢,我真的很感谢你回答我这个愚蠢的问题。这起作用了。我忽略了“属于”,因为它似乎无法描述这种关系,但我现在看到了Rails的情况。我同意,“属于”并不总是完全符合现实世界。它99%的时间都能工作。也许在宠物的情况下,记住谁在谁之后清理会有帮助:)