Reputation: 55283
This is how the user votes the current post that it is showing:
controllers/votes_controller.rb:
class VotesController < ApplicationController
def vote_up
@post = Post.find(params[:id])
if @post.votes.exists?(:user_id => current_user.id)
@notice = 'You already voted'
else
@vote = @post.votes.create(:user_id => current_user.id, :polarity => 1)
end
respond_to do |format|
format.js
end
end
This updates the total number of votes with Ajax:
vote_up.js.erb:
<% unless @notice.blank? %>
alert("<%= @notice %>");
<% end %>
<% unless @vote.blank? %>
$('.post-<%[email protected]%> span.vote-count').html('<%= @post.votes.count %>');
$('.post-<%[email protected]%> div.voted-user').html('<% @post.votes.each do |vote| %><%= link_to vote.user.username, vote.user %><% end %>');
<% end %>
This is the voting link in the show view:
views/posts/show.html.erb:
<%= link_to "Vote Up", vote_up_path(@post), :remote => true, :class => "vote-up" %><br />
and the routing for the action:
routes.rb:
get 'votes/:id/vote_up' => 'votes#vote_up', as: 'vote_up'
This is how all the posts are displayed in the index view:
views/posts/index.html.erb:
<% @posts.each do |post| %>
<h2>Title: <%= post.title %></h2>
<p>Author: <%= post.user.username %></p>
<p>Created At: <%= post.created_at %></p>
<p>Content: <%= post.content %></p>
<p>Votes: <%= post.total_votes %></p>
<p>Comments: <%= post.comments_count %></p>
<ul>
<li><%= link_to 'Show', post %></li>
<li><%= link_to 'Edit', edit_post_path(post) %></li>
<li><%= link_to 'Destroy', post, confirm: 'Are you sure?', method: :delete %></li>
</ul>
<br />
<% end %>
I would like to add the voting link in the index.html.erb
view for each post or find a way of triggering the vote_up
action for each post in the index view. Any suggestions to accomplish that?
Upvotes: 0
Views: 42
Reputation: 2478
I think I must be totally missing the point here but why can't you just do the following within the block displaying each post?
<%= link_to "Vote Up", vote_up_path(post), :remote => true, :class => "vote-up" %>
Note that i'm using post
not @post
.
Upvotes: 1