2014-10-17 78 views
0

我有一种情况,用户可以请求邀请,但前提是系统中没有请求。如果他们请求邀请,则invitation.sender_id设置为"0",并且如果他们收到来自用户的邀请,则invitation.sender_id设置为current_user.id,其始终为>0回调在Rails 3.2中没有像预期的那样工作

invitation.rb模型before_create :recipient_has_requested和回调:

def recipient_has_requested 
    if Invitation.exists?(recipient_email: :recipient_email, sender_id: 0) 
    errors.add :recipient_email, 'An invitation has already been sent to that email address.' 
    end 
end 

当我检查日志中的SQL,我看到:

Invitation Exists (0.0ms) SELECT 1 AS one FROM "invitations" WHERE "invitations"."recipient_email" = 'recipient_email' AND "invitations"."sender_id" = 0 LIMIT 1 

我的理解应该返回'true'回调,防止新的邀请被保存。但是,查看数据库显示我有多个邀请请求,全部来自同一个电子邮件地址,并且全部使用invitation.sender_id = 0

我是新来的,所以任何帮助将不胜感激。回调为什么会返回意想不到的结果?

==编辑==

我认为这里的逻辑是相反的。回调是找到符合条件的记录,因此返回true

任何人都可以看看逻辑并告诉我如何写它,所以它返回false

回答

0

好吧,在google-fu多了一些之后,我在SOF中遇到了一些类似的案例。

基本上,我的逻辑都错了。它被构建为回调,但逻辑是真实的。我将其更改为使用范围进行验证,并且工作正常。

下面是最终snipit:

validates :recipient_email, uniqueness: { scope: :sender_id } 
相关问题