Rails:为什么我的.each循环被跳过了?

时间:2015-07-24 19:18:12

标签: ruby-on-rails ruby loops

我从API一次收到一条新消息。每次收到新邮件时,我都希望在我的联系人模型中保存发件人的姓名(每个联系人所属的属性:用户,并且具有属性email,senderRealname和importancePoints)。对于每条消息,在我将发件人保存为新的联系人之前,我想检查当前用户的联系人以查看发件人是否已经在联系人列表中,这样我就不会保存任何重复的联系人。

由于某种原因,我的循环检查联系人是否已经存在,因此每个邮件的发件人都被保存为新联系人,无论它是否是重复的联系人。

以下是来自users_controller的代码:

response.each{|m| 
        messageId = m['message_id']
        body1 = m['bodies'][0]['content']
        senderName = m['addresses']['from'][0]['email']
        senderActualName = m['addresses']['from'][0]['name']
        recieveTime = m['sent_at']
        subjectText = m['subject']
        isRead = m['flags']['seen']
        hasReplied =  m['flags']['answered']
        importanceLevel = 0
        @contact_already_exists = 0

        @message_sender = senderName

        puts "RIGHT BEFORE CONTACTS"


        @user.contacts.each do |c|
            if c.email.to_s == @message_sender.to_s
                importanceLevel = c.importancePoints
                @contact_already_exists = 1
                puts "contact exists"
            else
                puts "contact does not exist"
            end
        end


        if @contact_already_exists == 1

            puts "No new contact"
        elsif @contact_already_exists == 0
            @newContact = Contact.new(email: senderName, realName: senderActualName, importancePoints: 0)
            @newContact.user = current_user
            @newContact.save
            puts "new contact saved"
        else

        end

- 然后我做其他工作正常工作的消息 -
对于每条消息,打印“正确的联系之前”文本,然后打印“新保存的联系人”文本。似乎整个循环检查是否存在联系人,因此@contact_already_exists永远不能设置为1.抱歉草率变量名称,仍然习惯于约定!

1 个答案:

答案 0 :(得分:2)

对不起,我刚读了你的长篇评论。

是的,@user设置在外部循环之外,因此在此循环的迭代中不会从数据库刷新/重新加载@user.contacts

您可以做两件事来解决这个问题,要么在循环的每次迭代中重新加载@user@user.reload以确保从数据库重新加载contacts,或者更改您构建新Contact以使用关联的方式,以便elsif成为:

elsif @contact_already_exists == 0
  @user.contacts.create(email: senderName, realName: senderActualName, importancePoints: 0)
  puts "new contact saved"

虽然我的原始答案不合适,但 对于检查create(或save)的返回或将其更改为{{1>仍然很重要替代方案,因此引发了异常。