I have built a blog application using Ruby on Rails. In the application I have posts and tags. Post has_many :tags and Tag belongs_to :post.
In the /views/posts/index.html view I want to display two things. First is a listing of all posts displayed 'created_at DESC' and then in the side bar I am wanting to reference my Tags table, group records, and display as a link that allows for viewing all posts with that tag.
UPDATE: The issue of duplicate posts being displayed and posts w/o tags not displaying have been fixed. Just trying to figure out now, how to handle the /posts?tag_name=foobar request such that only the posts with that tag are displayed.
UPDATED CODE: The posts are displaying properly, no duplication. The tag count is working correctly, and the tag groups are displaying as links and passing the tag_name into /posts?tag_name=new. I just can't get the link to trigger the display of only the posts that have those tags. FYI, the posts are identified in the tag table by post_id.
PostsController
def index
@tag_counts = Tag.count(:group => :tag_name, :order => 'updated_at DESC', :limit => 10)
@posts = Post.all( :order => 'created_at DESC' ).paginate :page => params[:page], :per_page => 4,
:conditions => (params[:tag_name] ?
{ :tags => {:tag_name => params[:tag_name]} } : {}
)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @posts }
format.json { render :json => @posts }
format.atom
end
end
View
Recently Used Tags
<table>
<% @tag_counts.each do |tag_name, tag_count| %>
<tr>
<td><%= link_to(tag_name, posts_path(:tag_name => tag_name)) %></td>
<td>(<%=tag_count%>)</td>
</tr>
<% end %>
</table>
<br>
<a href="/tags">click to view all tags >></a>
</div>
This screen shot might help (please note it is really ugly as just working on function) as it shows that there is only 1 tag in new but when the URL is hit, still displaying all posts.