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. -- Posted via http://www.ruby-forum.com/.
Ben Reubenstein
2006-May-08 02:28 UTC
[Rails] Queries with has_and_belongs_to_many relationship
Category.find(:first, :condition => "name = math").courses Or something to that effect should do the trick. On 5/7/06, Ben <whywontitletme@yahoo.com> wrote:> 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. > > -- > Posted via http://www.ruby-forum.com/. > _______________________________________________ > Rails mailing list > Rails@lists.rubyonrails.org > http://lists.rubyonrails.org/mailman/listinfo/rails >-- Ben Reubenstein 303-947-0446 http://www.benr75.com
Liquid
2006-May-08 02:29 UTC
[Rails] Re: Queries with has_and_belongs_to_many relationship
@courses_in_cat = Category.find_by_name(''math'', :first).courses This should give you back an array for all the courses in the math category. The opposite is also true. @categories_for_course = Course.find_by_name(''some course'', :first).categories To add Courses to a Category @some_category << @an_array_of_courses and vise versa @some_course << @an_array_of_categories On 5/8/06, Ben <whywontitletme@yahoo.com> wrote:> 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. > > -- > Posted via http://www.ruby-forum.com/. > _______________________________________________ > Rails mailing list > Rails@lists.rubyonrails.org > http://lists.rubyonrails.org/mailman/listinfo/rails >