Finding items in a Join Table


#1

Dear readers,

I’m very new to RoR, I walked trough the Agile Web D. 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

#2

This might work… it’s worth trying at least. :wink:

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

On Sun, Dec 28, 2008 at 9:25 AM, Rembrant
removed_email_address@domain.invalid wrote:

works better, because this code seems to fail frequently:
there is something way Rubier.

Any help would be greatly appreciated.

Kindest regards,

  • Rembrant


Robby R.
Chief Evangelist, Partner

PLANET ARGON, LLC
design // development // hosting w/Ruby on Rails


http://www.robbyonrails.com/
aim: planetargon

+1 503 445 2457
+1 877 55 ARGON [toll free]
+1 815 642 4068 [fax]