Rails 3: how to do database call for HABTM relationship
I setup a HABTM relationship between my post model, genre model, and genres_posts model. My genre model has a name:string attribute which consists of names like开发者_如何学JAVA 'thriller' 'western' 'horror' 'action' comedy' etc, when a user creates a post they can add 1 or more genres to the post.
I need to be able to list all of a user's posts by the specific genre, so they can easily switch back and forth between all their posts with genre 'western' and all the posts with genre 'action'.
Post.last.genres gives me the post's genres, but how would I do it for an array of a user's posts such as @user.posts ?? and then specify the specific genre name?
Is this the smartest way to do this type of thing?
In addition to ctcherry's answer, this is also possible:
@user.posts.joins(:genres).where(:genres => {:name => 'western'})
I assume your going to have a list of Genres somewhere, so you can get the Genre first, then get it's Posts filtered by user:
@genre = Genre.find_by_name('western')
@posts = @genre.posts.where(:user_id => @user.id)
精彩评论