开发者

Rails makevoteable help creating user voting link and custom error message

I am having that problem with the gem makevoteable that when the page is loaded the post gets upvoted automatic. Instead of just having a link the user can click and upvote. When the page is reloaded I get the AlreadyVotedError in view. I would prefer a more user friendly error message as "You already voted this post"

My view:

<% @posts.each do |post| %>
  <h1><%= post.titel %></h1>
  <p><%= post.body_html %></p>
  <p><%= link_to 'asdasdasd', current_user.up_vote(post) %>
<% end %> 

UPDATE:

My route.rb: match 'stem_op/:id' => 'posts#vote_up', :as => 'stem_op'

My public controller:

def vote_up
  @post = Post.find(params[:id])
  current_user.up_vote(@post)
  flash[:message] = 'Thanks for voting!'
  redi开发者_StackOverflow社区rect_to post_path(@post)
rescue MakeVoteable::Exceptions::AlreadyVotedError
  flash[:error] = 'Already voted!'
  redirect_to post_path(@post)
end

My view:

<% @posts.each do |post| %>
  <h1><%= post.titel %></h1>
  <p><%= post.body_html %></p>
  <p><%= link_to 'Stem op', stem_op_path(post.id) %> 
  </tr>
<% end %>

When I try to vote_up a post I get this error:

Template missing - Do I really need a blank view file?

UPDATE:

def vote_up
  @post = Post.find(params[:id])
  current_user.up_vote(@post)
  flash[:message] = 'Thanks for voting!'
  redirect_to post_path(@post)
rescue MakeVoteable::Exceptions::AlreadyVotedError
  flash[:error] = 'Already voted!'
  redirect_to post_path(@post)
end

Error:

SyntaxError in PostsController#vote_up

C:/Rails/den/app/controllers/posts_controller.rb:103: syntax error, unexpected keyword_end, expecting $end


Yes, current_user.up_vote(post) adds a vote for that user. You need to create a controller action that executes current_user.up_vote(post) and handles the flash message. Then you can link to that action in your view.

Edit to answer comment:

guides.rubyonrails.org/action_controller_overview

In your posts controller I imagine you would want something like:

def upvote
  @post = Post.find params[:id]
  current_user.upvote(@post)
  flash[:message] = 'Thanks for voting!'
  redirect_to post_path(@post)
rescue MakeVoteable::Exceptions::AlreadyVotedError
  flash[:error] = 'Already voted!'
  redirect_to post_path(@post)
end

and in your routes something like:

map.resource :post do
  member do
    post :upvote
  end
end

Your link would become link_to 'Upvote!', upvote_post_url(post), :method => :post

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜