'How to create multiple models in one action in the Right Way?(Ruby on Rails 5)

In fact, this issue keep popping up in my mind when I write the code that there are multiple models in one action.

In create, update action that I found besides using the association build API, otherwise I can't avoid that when one model failed but the others was success and they already exist then I can't redemption or revocation them.

The situation is as follows : Remove an good from the warehouse when an order is created. And the order is not actually related to the goods in the warehouse

I provide some simple examples of this issue:

def create
    @order = PackageOrder.new(order_params)
   
    if @order.save
        stock_record = PackageStockRecord.new(stock_record_params)
        if stock_record.save
            msg = 'stock_record saving success'
        else
            $ERROR.error "stock_record: #{stock_record.error_msgs}"
            msg = 'stock_record saving failed'
        end
        redirect_to action: 'index', msgs: msg
    else
        $ERROR.error "package_order: #{@order.error_msgs}"
        flash.now[:error] = 'package_order create failed.'
        render 'new'
    end
end

From the above example, it can be found that when @order is created or updated successfully, subsequent models can no longer affect or inform it. (except build api

So what I want is to undo the action of previous models and make it be notified when subsequent models was failed in the Right Way. (not by using the build api)

Or is it possible to create a short-lived association?

Is this normal? I mean is this situation inevitable or may be accumulated to cause system errors, or maybe I shouldn't care about it.

Are there relevant documents or procedures that can be learned in this situation?



Solution 1:[1]

If you want a model to be affected by changes in another model then that's done through association after all model is just class mapped to the table so you interact with the table in the ruby code.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shaher Shamroukh