I have created a simple blog application using Ruby on Rails, both of which I am new to. I am trying to get my most 'voted' posts to display in my /views/posts/index.html.erb view. Here are the basics.
I have created a votes table and successfully allow a user to 'vote' for a post on the /views/posts/show.html.erb page. The VotesController passes the post_id to the Votes table column post_id and returns the vote count for that post via ajax to the same show page.
class Vote
belongs_to :post`
end
and
class Post
has_many :votes
end
I would like to display in /views/posts/index.html.erb the post title and the amount of times it has been voted for, ordered by posts with the highest vote count.
EDIT With the code below I have been able to display (in the /views/posts/show.html.erb page) the post_id from the Votes table and vote_count for that post_id. i.e. '55(7)'. Wondering if somehow I can also pass the post_title to the votes table (to column post_title) and then just display that instead of the post_id. Here is the code that is accomplishing that.
class PostsController < ApplicationController
def index
@tag_counts = Tag.count(:group => :tag_name,
:order => 'count_all DESC', :limit => 20)
@vote_counts = Vote.count(:group => :post_id, :limit => 5)
conditions, joins = {}, nil
unless(params[:tag_name] || "").empty?
conditions = ["tags.tag_name = ? ", params[:tag_name]]
joins = :tags
end
@posts=Post.all(:joins => joins, :conditions=> conditions, :order => 'created_at DESC').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
VotesController
class VotesController < ApplicationController
def create
@post = Post.find(params[:post_id])
@vote = @post.votes.create!(params[:vote])
respond_to do |format|
format.html { redirect_to @post}
format.js
end
end
end
/views/posts/index.html.erb
Most Liked Posts<hr/>
<% @vote_counts.each do |post_id, vote_count| %>
<div id="tag-wrapper">
<%= link_to(post_id, posts_path(:post_id => post_id)) %>
(<%=vote_count%>)</div>
<% end %>