2

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 '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?

trying_hal9000
  • 4,343
  • 8
  • 43
  • 62

2 Answers2

1

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)
Chris Cherry
  • 28,118
  • 6
  • 68
  • 71
1

In addition to ctcherry's answer, this is also possible:

@user.posts.joins(:genres).where(:genres => {:name => 'western'})
Mischa
  • 42,876
  • 8
  • 99
  • 111