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

时间:2015-12-16 21:04:59

标签: ruby-on-rails associations has-many-through has-many

让我说我的Rails应用程序中有3个模型...建立,废物类型和建立废物......我的问题是我想获取与某种废物类型相关的所有企业 。这通常是Establishment.where(waste_type_id: some_number)完成的,问题是企业有很多废弃物类型,反之亦然,而且关联是通过第三方进行的......

任何帮助?

下面的类和数据模型

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

所以数据模型就像这些

1 个答案:

答案 0 :(得分:2)

在这种情况下,

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

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

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