0

当用户在没有先登录的情况下尝试投票时,我收到此错误:

nil:NilClass 的未定义方法“vote_for”

我有一个常规的“帖子”脚手架,用户正在对帖子进行投票。如果他们尚未登录,如何插入将他们重定向到 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
4

1 回答 1

2

before_filter :authenticate_user!你的PostController. 在该authenticate_user!方法中检查用户会话,如果用户未登录,则重定向到sign_in路径。

编辑:因为您已经有设计添加before_filter应该注意重定向以登录路径,如果用户未登录。以下仅适用于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
于 2013-07-13T03:32:01.213 回答