【问题标题】:I want to add a row if not found, update if it is found如果找不到我想添加一行,如果找到则更新
【发布时间】:2020-07-08 11:28:12
【问题描述】:

如果找不到people,以下代码将正确插入新行。如果找到people,我希望它更新现有行以及import_id,但更新不起作用。所以基本上如果一个新的导入在people 中包含相同的数据,我只想更新import_idpeoplename age

    Person.transaction do
      people.flatten.each do |people|
        Person.create_with({ import_id: import.id, **people }).find_or_create_by(**people)
      end
    end

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 activerecord


    【解决方案1】:

    要重申要求,如果 people 中的某个项目与 nameage 中的 Person 匹配,请更新该人的 import_id。如果people 中的该项与nameage 中的Person 不匹配,则创建一个新的Person 并设置import_id

    这应该可以满足您的需求。

    Person.transaction do
      people = [{ name: 'Tom', age: 20 }, { name: 'Jerry', age: 20 }]
      people.flatten.each do |person|
        Person.find_or_create_by(name: person[:name], age: person[:age])
          .update_attributes(import_id: import.id)
      end
    end
    

    通过所需属性查找或创建人员,然后更新新记录或现有记录上的import_id

    find_or_create_by docs

    【讨论】:

    • 实际上,通过一些测试,我发现了一个问题。似乎一个新人需要 import_id (必需)所以我猜 find_or_create 属性(名称,年龄)也需要 import_id 这将破坏更新,因为永远找不到 import_id。
    • @icantcode 我明白了。在这种情况下,删除!Person 在没有导入 ID 时将无效,并在使用 update_attributes 更新时生效。我已经更新了示例。
    猜你喜欢
    • 2010-10-20
    • 2017-06-09
    • 2022-11-15
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 2014-07-04
    • 1970-01-01
    相关资源
    最近更新 更多