[英]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. 我在gem makevoteable上遇到了问题,即页面加载后帖子会自动更新。 Instead of just having a link the user can click and upvote.
用户可以单击并投票,而不仅仅是链接。 When the page is reloaded I get the AlreadyVotedError in view.
重新加载页面后,我看到了AlreadyVotedError。 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'
我的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!'
redirect_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. 是的,
current_user.up_vote(post)
为该用户添加了一个投票。 You need to create a controller action that executes current_user.up_vote(post)
and handles the flash message. 您需要创建一个控制器操作,该操作执行
current_user.up_vote(post)
并处理该Flash消息。 Then you can link to that action in your view. 然后,您可以链接到视图中的该操作。
Edit to answer comment: 编辑以回答评论:
guides.rubyonrails.org/action_controller_overview 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
您的链接将变为
link_to 'Upvote!', upvote_post_url(post), :method => :post
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.