Patricio S
Patricio S

Reputation: 2130

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

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...

Any help?

Classes and data model below

enter image description here

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

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

So the data model would be like these

Upvotes: 3

Views: 30

Answers (1)

Oss
Oss

Reputation: 4322

EstablishmentWaste is a join table in this case so the query should be.

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.

Upvotes: 2

Related Questions