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

时间:2015-07-07 10:20:15

标签: ruby-on-rails ruby

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

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

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

2 个答案:

答案 0 :(得分:1)

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

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

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

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

答案 1 :(得分:-1)

如果你使用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