【问题标题】:rails update field based on find in another table基于在另一个表中查找的rails更新字段
【发布时间】:2017-06-26 18:34:06
【问题描述】:

我有一个用户模型(has_many contacts)和一个联系人模型(belongs_to user)。要发送邀请,我需要知道用户表中是否已存在用户的联系人并更新联系人中的状态字段。我的常用字段是电话号码。

我过于简单化了:

用户:身份证,电话

联系人:id、姓名、电话、状态、user_id

如何有效地将用户联系人的状态设置为“已注册”?

我目前有这个迭代,它有效,但必须有更好的方法:

all_contacts = Contact.where(user_id: user).where.not(phone: nil)
all_contacts.each do |contact|
  a = User.find_by(phone: contact.phone)
  if a
    contact.status = 'registered'
    contact.save
  end
end

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    您可以尝试以下操作:

    contacts = Contact.joins(:user).where("users.phone=contacts.phone and contacts.phone not NULL")
    contact_ids = fetch ids from contacts array
    Contact.update(your_array_of_ids, status: "registered")
    

    【讨论】:

    • 谢谢!这正是我一直在寻找的。这样,就不需要迭代了。 join 和 where 子句处理查找注册为用户的联系人。数据库在这类事情上非常有效,根据需要使用索引和内存。
    【解决方案2】:

    如果您只想在用户有电话号码的情况下将其状态更新为“已注册”,那么您可以将他们的 id 存储在一个数组中(例如使用where,然后您可以使用update 方法像这样:

    User.update(your_array_of_ids, status: "registered")
    

    【讨论】:

    • 我认为您误解了这个问题。如果用户表中存在联系人的电话号码,我想更新每个联系人的状态
    猜你喜欢
    • 1970-01-01
    • 2022-12-12
    • 2014-12-25
    • 2020-09-29
    • 2013-06-12
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    相关资源
    最近更新 更多