user3015195
user3015195

Reputation: 169

Rails querying a has_many through relationship

I have a has_many through relationship in my models and I am having trouble writing the query. Categories has four model attributes, (mens, women, t-shirts and hoodies) that each have products in them. What I would like to do is find a way to query all the products that belong in a specific category (for example all mens products) and then use that result in a loop to display the product data in my view.

My model structure is below.

Thanks for the help!

My Product model

class Product < ActiveRecord::Base
 has_many :options, dependent: :destroy
 has_many :images, dependent: :destroy

 has_many :categorizations
 has_many :categories, through: :categorizations

 def image_url
  self.images.first.url
 end

 def has_image?
  self.images.exists?
 end

end

My category model

class Category < ActiveRecord::Base
 has_many :categorizations
 has_many :products, through: :categorizations
end

My Categorizations model

class Categorization < ActiveRecord::Base
 belongs_to :category
 belongs_to :product
end

Upvotes: 1

Views: 108

Answers (1)

infused
infused

Reputation: 24337

To loop through each category's products:

Category.all.each do |category|
  category.products.each do |product|
    puts product
  end
end

Or find a single category and loop through it's products:

category = Category.find(2)
category.products.each do |product|
  puts product
end

Upvotes: 1

Related Questions