首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Rails Thumbs_up重定向到用户登录

Rails Thumbs_up重定向到用户登录
EN

Stack Overflow用户
提问于 2013-07-13 03:24:18
回答 1查看 200关注 0票数 0

当用户尝试投票而不首先被登录时,我会收到这个错误:

用于nil:nil类的未定义方法`vote_for‘

我有一个定期的“邮政”脚手架和用户正在投票的帖子。如果尚未登录,如何插入重定向到user_sign_in的命令?

代码语言:javascript
运行
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-13 03:32:01

在您的before_filter :authenticate_user!中添加一个PostController。在authenticate_user!方法中,检查用户会话,如果用户没有在重定向到sign_in路径中签名。

编辑:正如您已经设计好的,如果用户没有登录,添加before_filter应该负责重定向以登录路径。以下仅适用于vote_up操作,如果希望对所有操作都采用相同的行为,则可以用before_filter :authenticate_user!替换行

代码语言:javascript
运行
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17626674

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档