当用户尝试投票而没有先登录时,我收到此错误:
未定义的方法`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
答案 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