0

我目前正在设置一个用户模型,并且我有一个设置,新用户通过电子邮件发送激活令牌。当他们点击链接时,被调用的控制器方法有一行

@user = User.find_by_activation_token! params[:activation_token]

现在我的激活令牌有一个 24 小时的有效期,如果它已经过期,我希望用户记录被销毁。这对我来说很容易在控制器中实现,但我正在努力成为一个更好的 Rails 开发人员和更好的 Ruby 程序员,所以我认为我应该把它放在模型中(瘦控制器,胖模型!)。我认为它也能让我更好地了解类方法。

我对此进行了几次尝试,但都非常不成功。这是我迄今为止的最大努力;

def self.find_by_activation_token!(activation_token)
  user = self.where(activation_token: activation_token).first #I also tried User.where but to no avail
  if user && user.activation_token_expiry < Time.now
    user.destroy
    raise ActivationTokenExpired
  else
    raise ActiveRecord::RecordNotFound
  end
  user
end

我是否必须做出很多改变才能让它做我想做的事情,还是我完全走错了路?

4

1 回答 1

2

我想我明白了。你的条件逻辑有点不对劲

def self.find_by_activation_token!(activation_token)
  user = self.where(activation_token: activation_token).first #I also tried User.where but to no avail
  # if this user exists AND is expired
  if user && user.activation_token_expiry < Time.now
    user.destroy
    raise ActivationTokenExpired
  # otherwise (user does not exist OR is not expired)
  else
    raise ActiveRecord::RecordNotFound
  end
  user
end

我认为应该更像这样:

def self.find_by_activation_token!(activation_token)
  user = self.where(activation_token: activation_token).first #I also tried User.where but to no avail

  raise ActiveRecord::RecordNotFound unless user

  if user.activation_token_expiry < Time.now
    user.destroy
    raise ActivationTokenExpired
  end

  user
end
于 2012-06-13T13:29:12.170 回答