2012-06-13 84 views
0

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

@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 

我需要改变很多才能做到我希望做的事,或者我完全错误吗?

+0

为什么这不是为你工作? –

+0

好点。如果我调用User.find_by_activation_token!(valid_token),我会得到一个RecordNotFound异常。我的self.where(activation_token:activation_token)似乎有问题。 – brad

+0

是的。这里有一些控制台输出来演示。 https://gist.github.com/2924053 – brad

回答

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 
+0

是的,这工作得很好。我被束缚在思维班的方法中,比他们更特别,我没有停下来看看我的代码。我很尴尬但很感激。感谢这么快速的回应。 – brad

+0

出于兴趣,这是一种合理的方式来做我在做什么?从建筑适宜性的角度来看。 – brad

+0

@brad:看起来很适合我。虽然我个人会在定期的后台工作中清除过期账户。 –