redirect_to root_url并返回,除非@ user.activated

这是我的users_controller方法。 如果未激活用户,则应重定向。

 def show @user = User.find(params[:id]) redirect_to root_url and return unless @user.activated? end 

在这里我不理解方法中返回的需要,因为它会在执行redirect_to之前自动发生。 我见过很多例子,但大多数都有if语句,所以return会跳过这些检查。 在这里,有必要吗?

return语句在这里没有任何意义。 你可以写

 def show @user = User.find(params[:id]) redirect_to(root_url) unless @user.activated? end 

return语句有时用作避免双重渲染问题的技巧,尤其是使用显式render 。 举个例子:

 def show @user = User.find(params[:id]) redirect_to(some_url) unless @user.activated? redirect_to(other_url) unless @user.other? render action: "hello" end 

如果您不在此处使用return,则在方法返回时,您可能会定义渲染行为两次甚至三次。

一般来说,带有返回的多次渲染是编码气味的标志。 如果任何操作设置了渲染行为,您通常可以在用于停止执行链的操作之前重构操作以正确使用。

如果您使用Devise ,您可以写:

  # GET /users/:id.:format def show # authorize! :read, @user end 

默认情况下它是可行的。

更新 。 注意:如果您必须通过电子邮件启用激活,您可以写:

在device.rb中(找到此字符串并取消注释):

  # ==> Configuration for :confirmable # A period that the user is allowed to access the website even without # confirming his account. For instance, if set to 2.days, the user will be # able to access the website for two days without confirming his account, # access will be blocked just in the third day. Default is 0.days, meaning # the user cannot access the website without confirming his account. config.confirm_within = 2.days # Defines which key will be used when confirming an account config.confirmation_keys = [ :email ] 

在用户模型中(添加到device string ):

 device ..., :comfirmable