Let's say I have 3 models in my Rails app... Establishment, WasteType and EstablishmentWaste... My problem is that I want to get all establishments associated with a certain wastetype. This normally would be done with Establishment.where(waste_type_id: some_number)
, the problem is that Establishment has many WasteType and vice versa, and the association is made through a third party...
假设我有3个模型在我的Rails应用中…建立,WasteType EstablishmentWaste……我的问题是我想要所有与某种废物类型相关的设施。这通常是建立起来的。在(waste_type_id: some_number)中,问题是建立有很多的废物类型,反之亦然,关联是通过第三方建立的……
Any help?
任何帮助吗?
Classes and data model below
类和数据模型如下
Establishment
建立
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
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
EstablishmentWaste
class EstablishmentWaste < ActiveRecord::Base
belongs_to :establishment, :foreign_key => 'establishment_id'
belongs_to :waste_type, :foreign_key => 'waste_type_id'
end
So the data model would be like these
数据模型是这样的
1 个解决方案
#1
2
EstablishmentWaste
is a join table in this case so the query should be.
在这种情况下,builshmentwaste是一个连接表,因此查询应该是。
Establishment
.joins(:establishment_wastes)
.where('establishment_wastes.waste_type_id = ?', some_number)
Quick tip! You do not need to assign :foreign_key => 'establishment_id'
since it is default Rails behavior to assign a foreign key to model_id
.
快提示!您不需要分配:foreign_key => ' builshment_id ',因为它是为model_id指定一个外键的默认Rails行为。
#1
2
EstablishmentWaste
is a join table in this case so the query should be.
在这种情况下,builshmentwaste是一个连接表,因此查询应该是。
Establishment
.joins(:establishment_wastes)
.where('establishment_wastes.waste_type_id = ?', some_number)
Quick tip! You do not need to assign :foreign_key => 'establishment_id'
since it is default Rails behavior to assign a foreign key to model_id
.
快提示!您不需要分配:foreign_key => ' builshment_id ',因为它是为model_id指定一个外键的默认Rails行为。