簡體   English   中英

Rails makevoteable幫助創建用戶投票鏈接和自定義錯誤消息

[英]Rails makevoteable help creating user voting link and custom error message

我在gem makevoteable上遇到了問題,即頁面加載后帖子會自動更新。 用戶可以單擊並投票,而不僅僅是鏈接。 重新加載頁面后,我看到了AlreadyVotedError。 我希望收到更人性化的錯誤消息,例如“您已對此帖子投了票”

我的觀點:

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

更新:

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

我的公共控制器:

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

我的觀點:

<% @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 %>

當我嘗試對一個帖子進行表決時,出現此錯誤:

缺少模板-我真的需要一個空白的視圖文件嗎?

更新:

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

錯誤:

SyntaxError in PostsController#vote_up

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

是的, current_user.up_vote(post)為該用戶添加了一個投票。 您需要創建一個控制器操作,該操作執行current_user.up_vote(post)並處理該Flash消息。 然后,您可以鏈接到視圖中的該操作。

編輯以回答評論:

guides.rubyonrails.org/action_controller_overview

在您的帖子控制器中,我想您會想要以下內容:

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

在您的路線中,例如:

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

您的鏈接將變為link_to 'Upvote!', upvote_post_url(post), :method => :post

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM