I cant seem to find a way to do this. Some guidance would be great!
I’m building a blog like site with posts and posts contain tags. The tags and posts are held together by a join table. I can access them via post.tags.
Im trying to put together a search to display all posts containing a certain tag.
After trying for awhile this is the best I came up with:
def tag
tag = Tag.find_by_title(params[:id])
p = Post.page(params[:page]).per_page(7).all
@posts = Array.new
p.each do |p|
if p.tags.include? (tag)
@posts << p
end
end
This works all except the pagination. Im thinking there has got to be a simple where clause to simplify this?
Thanks!
Edit:
Here is my join table

The next method should return the array of post tagged with the tag :
You just have to keep the first line of your method and add the line above after.
Notice that to make it working you should have defined the relationships between your post and tag in your model with an
has_and_belongs_to_many.