2015-12-16 81 views
3

比方說,我的Rails應用程序中有3個模型...建立,浪費類型和建立垃圾...我的問題是我想要獲取與所有相關的機構某種垃圾類型。這通常會與Establishment.where(waste_type_id: some_number)完成,問題是,建立了許多廢物類型,反之亦然,並通過第三方協會...獲取某條件滿足兩條條件的記錄has_many:通過

任何幫助嗎?

類和數據模型下面

enter image description here

建立

class Establishment < ActiveRecord::Base 
    # Include default devise modules. 
    devise :database_authenticatable, :registerable, 
      :recoverable, :rememberable, :trackable, :validatable, :omniauthable 

    has_many :containers 
    has_many :establishment_wastes 
    has_many :waste_types, through: :establishment_wastes, :foreign_key => 'establishment_id' 

    include DeviseTokenAuth::Concerns::User 
end 

WasteType

class WasteType < ActiveRecord::Base 

    has_many :containers 
    has_many :establishment_wastes 
    has_many :establishments, through: :establishment_wastes, :foreign_key => 'waste_type_id' 

end 

EstablishmentWaste

class EstablishmentWaste < ActiveRecord::Base 

    belongs_to :establishment, :foreign_key => 'establishment_id' 
    belongs_to :waste_type, :foreign_key => 'waste_type_id' 

end 

因此,數據模型應該是這樣的

回答

2

EstablishmentWaste在這種情況下連接表,以便查詢應該是。

Establishment 
.joins(:establishment_wastes) 
.where('establishment_wastes.waste_type_id = ?', some_number) 

快速提示!您不需要分配:foreign_key => 'establishment_id',因爲默認的Rails行爲可將外鍵分配給model_id