【问题标题】:Rails create or update for associated recordsRails 为关联记录创建或更新
【发布时间】:2019-03-22 10:10:26
【问题描述】:

我有这个引发“重复预期”的示例代码。相反,如果存在重复,我只想跳过。

(1..10).each do |page|
      group.products << [{id: 1, title: "Example A"}, {id: 2, title: "Example B"}]
      group.save
end

产品数组对于这个例子来说是静态的,重要的是它有ID,所以产品存在于数据库中。

问题是,当我分配过去已分配的产品时,会引发“非唯一异常”。在这种情况下,我会跳过关联。这怎么可能?

【问题讨论】:

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


    【解决方案1】:

    您可以将create_withfind_or_create_by 结合使用:

    (1..10).each do |page|
      group.products << Product.create_with(title: "Example A").find_or_create_by(id: 1)
      group.products << Product.create_with(title: "Example B").find_or_create_by(id: 2)
      group.save
    end
    

    【讨论】:

      【解决方案2】:

      您在创建重复项的十次循环中将相同的动态对象数组分配给group.products。你为什么不运行这个没有循环?我认为不需要循环。

      【讨论】:

      • OP 不想跳过验证,而是避免添加重复记录的解决方案
      【解决方案3】:

      其他选项可能是使用first_or_initialize:

      (1..10).each do |page|
        group.products << Product.where(id: 1).first_or_initialize(title: "Example A").save
        group.products << Product.where(id: 2).first_or_initialize(title: "Example B").save
        group.save
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多