How to display acts_as_taggable tags on a page with the posts underneath each tag in Rails?

632 views Asked by At

I am using the gem acts_as_taggable_on. I have it setup and working correctly. I am trying to create a page that lists all the tags with the posts underneath each tag they belong to?

(Tag 1)

  • Post tagged with tag 1
  • Post tagged with tag 1
  • Post tagged with tag 1

(Tag 2)

  • Post tagged with tag 2
  • Post tagged with tag 2
  • Post tagged with tag 2

(Tag 3)

  • Post tagged with tag 3
  • Post tagged with tag 3
  • Post tagged with tag 3

Here is my code i have all the tags showing on one page but i can't get the posts to show underneath the tag?

Tags Controller:

def index
    @tag   = current_user.owned_tags
    @posts = current_user.posts.tagged_with(@tag.name)
end

Tags Index View:

<div class="tag-lists">
    <% @tag.each do |tag| %>

        <div><%= tag.name %></div>

        <% @posts.each do |post| %>
            <div><%= post.title %></div>
        <% end %>

    <% end %>
</div>
1

There are 1 answers

8
rorra On BEST ANSWER

You need to iterate each one of the posts per tag

on your controller:

def index
    @user  = current_user
    @tags  = @user.owned_tags
end    

on your view:

<div class="tag-lists">
    <% @tags.each do |tag| %>

        <div><%= tag.name %></div>

        <% @user.posts.tagged_with(tag.name).each do |post| %>
          <div><%= post.title %></div>
        <% end %>

    <% end %>
</div>