2016-05-24 204 views
0

我通過關聯has_many有問題。rails 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

第二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 
相關問題