Finding items in a Join Table

Dear readers,

I'm very new to RoR, I walked trough the Agile Web Development With Rails book, but I still got stuck. I'm trained as a designer, so coding isn't really my branch but I try to get by. Anyways, here is my question.

I set up 3 tables including one join table like this:

class Category < ActiveRecord::Base   has_many :products   has_many :brands, :through => :products, :uniq => true end

class Brand < ActiveRecord::Base   has_many :products   has_many :categories, :through => :products end

class Product < ActiveRecord::Base   belongs_to :category   belongs_to :brand end

I can easily find brands belonging to a certain category doing this:

@brands = Category.find(session[:selected_category]).brands

(it gets the session var from a link_to_remote's params[:id])

But now I'm trying to find all the products that belong to a certain brand and a certain category, so for example only Laptops (category) made by Apple (brand). This is the code I've got this far, but I'm sure there must be something more elegant and something that just works better, because this code seems to fail frequently:

@products = Product.find(:all, :conditions => "category_id = '#{session [:selected_category].id}' AND brand_id = '#{session [:selected_brand].id}'")

This doesn't look too crazy from what I remember from mysql, but I bet there is something way Rubier.

Any help would be greatly appreciated.

Kindest regards,

- Rembrant

This *might* work... it's worth trying at least. :wink:

@products = Brand.find( brand_id ).categories( category_id ).products