rails has_many:通过关联不起作用

时间:2016-05-24 10:53:41

标签: ruby-on-rails associations

我有一个关于has_many的问题。

我有一个帐户模型,有很多办公室和酒店 account.rb:

class Account < ActiveRecord::Base

  # associations
  has_many :partnerships, through: :hotels, dependent: :destroy
  has_many :partnerships, through: :offices, dependent: :destroy
  has_many :users, through: :hotels, dependent: :destroy
  has_many :hotels, dependent: :destroy
  has_many :offices, dependent: :destroy
  belongs_to :admin, class_name: "User", foreign_key: "admin_user_id", dependent: :destroy

然后我有一个合作伙伴表,这是酒店和办公室之间的联接表 因此,酒店和办公室都有很多合作关系:

class Hotel < ActiveRecord::Base
  has_many :partnerships
  belongs_to :account
  has_and_belongs_to_many :user

 class Office < ActiveRecord::Base
  belongs_to :account
  has_and_belongs_to_many :users
  has_many :partnerships

最后我的伙伴关系模式:

class Partnership < ActiveRecord::Base

  belongs_to :hotel
  belongs_to :office

然而,当我测试帐户与合作伙伴关系与拥有酒店合作伙伴关系(@account.partnerships)的帐户之间的关联时,我得到一个空的[],而当我直接使用相关的酒店时(@hotel.partnerships ),我得到了我的相关合作伙伴名单。

你能告诉我为什么这些协会不起作用:

 has_many :partnerships, through: :hotels, dependent: :destroy
 has_many :partnerships, through: :offices, dependent: :destroy

1 个答案:

答案 0 :(得分:1)

第二个has_many :partnerships覆盖第一个。

has_many :partnerships, through: :hotels, dependent: :destroy # 1
has_many :partnerships, through: :offices, dependent: :destroy # 2

解决这个问题的方法是在协会前加上:

has_many :hotel_partnerships, through: :hotels, source: :partnerships, dependent: :destroy
has_many :office_partnerships, through: :offices, source: :partnerships, dependent: :destroy