我从 API 一次收到一条新消息。每次收到新消息时,我都想将发件人的姓名保存在我的联系人模型中(每个联系人都属于 :user,并且具有电子邮件、发件人真实姓名和重要性点属性)。对于每条消息,在我将发件人另存为新联系人之前,我想检查当前用户的联系人以查看发件人是否已经在联系人列表中,这样我就不会保存任何重复的联系人。
出于某种原因,我检查联系人是否已存在的循环被跳过,因此每条消息的发件人都被保存为新联系人,无论它是否是重复联系人。
这是来 self 的 users_controller 的代码:
response.each do |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'
end
end
--然后我用工作正常的消息做其他事情--
对于每条消息,“RIGHT BEFORE CONTACTS”文本被打印,然后“new contact saved”文本被打印。似乎跳过了检查联系人是否存在的整个循环,因此永远不能将 @contact_already_exists 设置为 1。对于草率的变量名称感到抱歉,仍然习惯约定!
最佳答案
抱歉,我刚刚看了你的长评论。
是的,@user
设置在外循环之外,因此 @user.contacts
不会在此循环的迭代中从数据库中刷新/重新加载。
你可以做两件事来解决这个问题,要么在循环的每次迭代中重新加载你的@user
:@user.reload
以确保联系
从数据库中重新加载,或者更改您构建新 Contact
的方式以使用关联,因此您的 elsif
变为:
elsif @contact_already_exists == 0
@user.contacts.create(email: senderName, realName: senderActualName, importancePoints: 0)
puts "new contact saved"
虽然我最初的回答是离题的,但检查create
(或save
)或更改的返回值仍然很重要它到 !
替代方案,因此会引发异常。
关于ruby-on-rails - Rails : Why is my . 每个循环都被跳过了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31618200/