This may have been asked/answered before - if so, i apologise…
I have the following table layout in a habtm relationship:
| products | ----| categories_products |-----| categories |
What would be the best way to pull out all the products for a given
category? At the moment, i’ve got it going by specifing a join manually
in the find() but that just doesn’t seem groovey enough for Rails :0)
Cheers,
Steve
On May 1, 2006, at 11:26 AM, Stephen B. wrote:
This may have been asked/answered before - if so, i apologise…
FYI, this is just about as Rails 101 as you can get…
I have the following table layout in a habtm relationship:
| products | ----| categories_products |-----| categories |
What would be the best way to pull out all the products for a given
category? At the moment, i’ve got it going by specifing a join
manually in the find() but that just doesn’t seem groovey enough
for Rails :0)
Assuming that you have:
has_and_belongs_to_many: products
In your Category model class definition, you can simply do:
@category = Category.find(1)
@products = @category.products
That will give you an array of Product items, all of them associated
with that particular Category. This, and a whole lot more is
explained in the API docs: rails.rubyonrails.org. Find the link on
the left for ActiveRecord::Associations.
-Brian
That’s great thanks. I actually oversimplified my example as my
products actually have a habtm relationship with 2 tables: products ->
activities and destinations. I’ve used a join to search the 2 joiner
tables - works well!
Steve
Point taken - consider my wrist well and truly slapped :0)
Steve
On May 1, 2006, at 12:58 PM, Stephen B. wrote:
That’s great thanks. I actually oversimplified my example as my
products actually have a habtm relationship with 2 tables: products
→ activities and destinations. I’ve used a join to search the 2
joiner tables - works well!
Another quick FYI (not just for Steve, this is merely a convenient
example), if you want to get appropriate help/advice, please take the
time to explain the whole problem. The more information and context,
the easier it will be for the community to help you.
I know I shouldn’t have to say it, but, please don’t be a Help
Vampire: http://www.slash7.com/pages/vampires
Work well with the community, so that the community can work well
with you.
-Brian