Forum: Ruby on Rails Finding items in a Join Table

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Rembrant (Guest)
on 2008-12-28 20:35
(Received via mailing list)
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
Robby R. (Guest)
on 2008-12-28 21:12
(Received via mailing list)
This *might* work... it's worth trying at least. ;-)

@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.planetargon.com/
http://www.robbyonrails.com/
aim: planetargon

+1 503 445 2457
+1 877 55 ARGON [toll free]
+1 815 642 4068 [fax]
This topic is locked and can not be replied to.