通过两个 has_many :through 获取满足某个条件的记录

Obtaining records where a certain condition is satisfied with two has_many :through

假设我的 Rails 应用程序中有 3 个模型...Establishment、WasteType 和 EstablishmentWaste...我的问题是我想获取与特定废物类型关联的所有机构。这通常会用 Establishment.where(waste_type_id: some_number) 完成,问题是 Establishment 有很多 WasteType,反之亦然,关联是通过第三方建立的...

有什么帮助吗?

类 和下面的数据模型

机构

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

废物类型

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

所以数据模型会像这样

在这种情况下,

EstablishmentWaste 是一个连接 table,因此查询应该是。

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

快速提示!您不需要分配 :foreign_key => 'establishment_id',因为将外键分配给 model_id 是默认的 Rails 行为.