Searching through HABTM

Hey,   I have a model "story" that habtm genres (model - genre, table - genres, join_table genres_stories). How do I look for a story of a certain genre in a find condition?

JB

I have a model "story" that habtm genres (model - genre, table - genres, join_table genres_stories). How do I look for a story of a certain genre in a find condition?

story = Story.find(42) genres = story.find_all_by_name('whimsy') more_genres = story.find(:all, :conditions = 'name like "whim%"')

Now read

there's a reason that page lists all the various (mostly boring) methods that automatically get generated when you add an association!

I may be misunderstanding what you are saying, but what I am looking to do is essentially: stories = Story.find_all_by_genres("GENRE") where genres has a has_and_belongs_to_many relationship to story.

Thanks, JB

class Story < ActiveRecord::Base   has_and_belongs_to_many :genres end

class Genre < ActiveRecord::Base   has_and_belongs_to_many :stories end

Genre.find("mystery").stories

Of course, that should have been something like

Genre.find_by_name("mystery").stories

Assuming that Genre has a name attribute.

Thanks for the info guys,   Genre.find_by_name("genre").stories is close to what I want. Let me make it a bit more complex though now: I want to be able to take those stories of a certain genre and order them by rating or post date, and filter them by another factor which is category (and maybe even another parameter). So Story also HABTM categories and has a rating/post_date parameter. As the number of stories in a genre is going to grow largely it seems wildly inefficient to take the array of all the stories then increment though each one check to see if it is in the right category and sorting by date. What I really need is something like:

Story.find_by_genre_and_category_and_anotherthing("genre", "category", "anotherthing", :conditions => "post_date < somedate", :order => "rating DESC")

Anybody have any ideas?

Thanks, JB

Story.find_by_genre_and_category_and_anotherthing("genre", "category", "anotherthing", :conditions => "post_date < somedate", :order => "rating DESC")

Looks good. Try .find_all_by_...

If anotherthing is in another table, you will need to :include => :anotherthings, and you can't use an automatic method named _and_.

The problem I have is that f.find_all_by_ doesn't work. I have tried find_all_by_genre and I get: undefined method `find_all_by_genre' I tried find_all_by_genre("GENRE", :include => :genres and no dice.

JB

The problem I have is that f.find_all_by_ doesn't work. I have tried find_all_by_genre and I get: undefined method `find_all_by_genre' I tried find_all_by_genre("GENRE", :include => :genres and no dice.

If anotherthing is in another table, you will need to :include => :anotherthings, and you can't use an automatic method named _and_.

Read it again.