David Carpenter
David Carpenter

Reputation: 1640

Rails has_and_belongs_to_many query

I have the following database schema in my rails 4 application

Users >---Tags_users---< Tags >---Posts_tags---< Posts

given the currently logged in user, what is the best way for me to get all of the posts (from all users) that match there tags the tags that they are interested in.

Upvotes: 1

Views: 168

Answers (1)

Jorge de los Santos
Jorge de los Santos

Reputation: 4633

You can pass an array to Model#where to get an array of posts with the choosed criteria.

def show_by_tags
  @posts = Post.all
  array_of_tags.each do |tag|
    @posts.where(tag_name: tag)
  end
end

Upvotes: 2

Related Questions