【问题标题】:How to save 2 models in one transaction using ActiveModel?如何使用 ActiveModel 在一个事务中保存 2 个模型?
【发布时间】:2020-07-22 03:46:45
【问题描述】:

我有一个适用于 4 个模型的小班。我想以“正确”的方式做事。基本上,我想创建 2 个 Address 模型、1 个 Shipment(带有 2 个 address_ids 和属于 Shipment1 Parcel

在这一点上,我很困惑。我需要克服这一点并进入下一个重要里程碑。这看起来很有希望,还是您建议在控制器中保存 2 条记录,然后使用 after_create 或类似的东西?谢谢。

class Quote
  include ActiveModel::Model
  attr_accessor address_to: {
                  :name, :company, :street1, :street2, :street3, :city, :state, 
                  :zip, :country, :phone, :email},
                address_from: {
                  :name, :company, :street1, :street2, :street3, :city, :state, 
                  :zip, :country, :phone, :email
                }
  def save
    return false if invalid?

    ActiveRecord::Base.transaction do
      user = User.find_by(id: user_id)
      user.addresses.create!([{address_from, address_to}]) # how to do this?

    end
  end
end

【问题讨论】:

    标签: ruby-on-rails activerecord active-model-serializers


    【解决方案1】:

    如果您通过标签:belongs_to:has_many 使用模型关联, 例如,您可以使用accepts_nested_attributes_for :another_child_model。如果您在控制器上允许这些参数,它将自动创建或定义此关联。

    Rails guide for nested attributes

    注意在控制器上允许这些属性。

    class YourController < ApplicationController
       ...
       def your_params
          params.require(:entity).permit(:etc, :etc, child_model_attributes: [:id, :name, :etc, :etc])
       end
       ...
    end
    

    【讨论】:

      【解决方案2】:
      1. 切勿在模型上使用回调。模型难以测试,行为不可预测。
      2. 你可以使用accept_nested_attributes。
      3. 如果您有一个自定义逻辑,您可以使用服务对象模式并将所有逻辑放在那里。 但是,如果您想像您一样做,请尝试使用user.addresses.create!([address_from, address_to])

      【讨论】:

        【解决方案3】:

        如果您使用Rails 6 或更高版本 - 有一种称为insert_all 的方法可以在一个INSERT 语句中将多条记录插入数据库。

        在 apidock 上查看:insert_all

        例子:

        Book.insert_all([
          { id: 1, title: "Rework", author: "David" },
          { id: 1, title: "Eloquent Ruby", author: "Russ" }
        ])
        

        (来自文档的示例)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-10-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-12-01
          • 2020-05-18
          • 1970-01-01
          • 2018-04-19
          相关资源
          最近更新 更多