当用户尝试投票而不首先被登录时,我会收到这个错误:
用于nil:nil类的未定义方法`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发布于 2013-07-13 03:32:01
在您的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
endhttps://stackoverflow.com/questions/17626674
复制相似问题