dublicate display of Posts from controller - conditions and joins problem - Ruby on Rails
- by bgadoci
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.
With the code below, I am able to display the tag groups and succesfully display all posts with that tag. There are two problems with it thought.
/posts view, the code seems to be referencing the Tag table and displaying the post multiple times, directly correlated to how many tags that post has. (i.e. if the post has 3 tags it will display the post 3 times).
/posts view, only displays posts that have Tags. If the post doesn't have a tag, no display at all.
/views/posts/index.html.erb
<%= render :partial => @posts %>
/views/posts/_post.html.erb
<% div_for post do %>
<h2><%= link_to_unless_current h(post.title), post %></h2>
<i>Posted <%= time_ago_in_words(post.created_at) %></i> ago
<%= simple_format h truncate(post.body, :length => 300) %>
<%= link_to "Read More", post %> |
<%= link_to "View & Add Comments (#{post.comments.count})", post %>
<hr/>
<% end %>
/models/post.rb
class Post < ActiveRecord::Base
validates_presence_of :body, :title
has_many :comments, :dependent => :destroy
has_many :tags, :dependent => :destroy
cattr_reader :per_page
@@per_page = 10
end
posts_controller.rb
def index
@tag_counts = Tag.count(:group => :tag_name, :order => 'updated_at DESC', :limit => 10)
@posts=Post.all(:joins => :tags,:conditions=>(params[:tag_name] ?
{ :tags => { :tag_name => params[:tag_name] }} : {}
)
).paginate :page => params[:page], :per_page => 5
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @posts }
format.json { render :json => @posts }
format.atom
end
end