Ruby on Rails Thumbs_up重定向到用户登录

时间:2013-07-13 03:24:18

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 voting

当用户尝试投票而没有先登录时,我收到此错误:

  

未定义的方法`vote_for'为nil:NilClass

我有一个常规的“Post”脚手架,用户正在对帖子进行投票。如果他们尚未登录,如何插入将其重定向到user_sign_in的命令?

class PostsController < InheritedResources::Base
  def vote_up
  begin
  current_user.vote_for(@post = Post.find(params[:id]))
  redirect_to [@post]
  flash[:success] = "You have voted successfully"
rescue ActiveRecord::RecordInvalid
  redirect_to [@post]
  flash[:error] =  "You have already voted"
  end
 end

end

1 个答案:

答案 0 :(得分:2)

before_filter :authenticate_user!中添加PostController。在authenticate_user!方法中,检查用户会话,以及用户是否未重定向到sign_in路径。

编辑:正如您已经添加了before_filter的Devise,如果用户未登录,则应该注意重定向以登录路径。以下内容仅适用于vote_up操作,如果您对所有操作都喜欢相同的行为,然后您可以用before_filter :authenticate_user!

替换该行
class PostsController < InheritedResources::Base 
  # Add before_filter here and devise should handle the redirection if the user is not signed in.
  before_filter :authenticate_user!, only: [:vote_up]

  def vote_up
  begin
  current_user.vote_for(@post = Post.find(params[:id]))
  redirect_to [@post]
  flash[:success] = "You have voted successfully"
rescue ActiveRecord::RecordInvalid
  redirect_to [@post]
  flash[:error] =  "You have already voted"
  end
 end

end