Search code examples
ruby-on-railsactiverecordactive-model-serializers

How to save 2 models in one transaction using ActiveModel?


I have a little class that works with 4 models. I'd like to do things the "right" way. Basically, I want to create 2 Address models, 1 Shipment (w/ 2 address_ids, and 1 Parcel that belongs to Shipment.

At this point, I'm confused. I need to get past this and onto the next big milestone. Does this look promising, or do you recommends saving 2 records in the controller, then use an after_create, or something similar? Thank you.

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

Solution

  • If you are using Model association through the tags :belongs_to and :has_many, you could use accepts_nested_attributes_for :another_child_model for example. It will automatically create or define this association if you permit those params on the controller.

    Rails guide for nested attributes

    Pay attention on permitting those attributes on the controller.

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