Forum: Ruby on Rails Queries with has_and_belongs_to_many relationship

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
7813d26c8ef483e08432ec9c574664d6?d=identicon&s=25 Ben (Guest)
on 2006-05-08 04:23
I was able to create a has_and_belongs_to_many relationship for my app,
but now I'm not too sure how to write queries for it.

Basically, I have a table 'courses' that has_and_belongs_to_many
'categories' and vice versa

So I'm trying to figure out how I would find only the courses that
belong to a category that I specify.

Let's say the category is 'math' and the categories are in a column
named 'name'

Any help would be great.
D90ef6808433e63203e15a5c2dadb0bb?d=identicon&s=25 Ben Reubenstein (Guest)
on 2006-05-08 04:28
(Received via mailing list)
Category.find(:first, :condition => "name = math").courses

Or something to that effect should do the trick.

On 5/7/06, Ben <> wrote:
> named 'name'
> Any help would be great.
> --
> Posted via
> _______________________________________________
> Rails mailing list

Ben Reubenstein
9d1f5d2d9de70bd9a934f557dc95a406?d=identicon&s=25 Daniel ----- (liquid)
on 2006-05-08 04:32
(Received via mailing list)
@courses_in_cat = Category.find_by_name('math', :first).courses

This should give you back an array for all the courses in the math

The opposite is also true.

@categories_for_course = Course.find_by_name('some course',

To add Courses to a Category
@some_category << @an_array_of_courses
and vise versa
@some_course << @an_array_of_categories
This topic is locked and can not be replied to.