newUserNameHere
newUserNameHere

Reputation: 17971

Select values through many to many relationship in active record using "where"

I'm trying to get all the distict brands that have a part belonging to the category named car (category.name = "car"), through a many to many relationship.

Here are the models:

class Brand < ActiveRecord::Base
  has_many :brand_parts
  has_many :parts, through: :brand_parts
end

-

class Category < ActiveRecord::Base
  has_many :parts
end

-

class Part < ActiveRecord::Base
  belongs_to :category

  has_many :brand_parts
  has_many :brands, through: :brand_parts
end 

-

class BrandPart < ActiveRecord::Base
  belongs_to :brand
  belongs_to :part
end

Update: Answer below nailed it

Here's This is what I've got so far:

Part.joins(:category).joins(:brands).where(category: {name: 'car'}).select(brands.name).distinct

The query it outputs (listed below) works GREAT in PG admin but through active record instead of being able to see the brand names, I just get a result set that looks like this:

#<Part id: nil>
#<Part id: nil>
#<Part id: nil>

Upvotes: 2

Views: 2653

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

Has been tested by @newUserNameHere and actually working:

scope = Brand.joins(parts: :category).where(categories: { name: 'car' })
scope = scope.select('DISTINCT brands.name').order('brands.name')

brand_names_appearing_in_car_category = scope.map(&:name)

Upvotes: 3

Related Questions