Note that there are some explanatory texts on larger screens.

plurals
  1. POWhich part of Rails should take care of updating chained model statuses?
    primarykey
    data
    text
    <p>I have 2 models</p> <ol> <li>ShippingClass, which define a shipping fare and the destinations to which the shipping fare is applicable</li> <li>Shop, which has a state machine that determine if a number of actions are allowed or not</li> </ol> <p>A shop has_many shipping_classes. The user can add or delete shipping classes and, among other factors, the fact that at least one shipping_class exist or not has an impact on the shop state.</p> <p>The bottom line is that any time a shipping class is added/deleted/modified I run an update_state method on the shop model to keep the state up to date. What this method does is basically checking how many shipping_classes are associated to the shop and adjust the shop status accordingly (eg, to simplify the shop state is active if there is at least 1 shipping_class assigned, otherwise is inactive)</p> <p>I was wondering if it is good practice to update the shop state from the controller. I am in fact evaluating the opportunity of having the ShippingClass to update the Shop upon save and destroy. While this may be more error proof, as I don't need to remember to update the Shop model every time I save a ShippingClass, it however increases the coupling of the models. </p> <p>Using callbacks to do this appears not to be an option. These are wrapped into transaction. Therefore the parent model (Shop) does not see exactly what is the status of the associated models (ShippingClasses) before the transaction is completed.</p> <p>EDIT Another option, as pointed out below, is to place the model update into an observer. The advantage of this is that it is not wrapped into a transaction, so the Shop model should be able to check the associated ShippingClasses. The disadvantage is that is not wrapped into a transaction, so a failure to update the Shop model would desync the Shop status. This would, however be better than placing the update into the controller, as it would be done once forever.</p> <p>Another option could be override the save and destroy methods of ShippingClass and update the Shop model from there.</p> <p>What is the best practice and why?</p> <p>THanks in advance</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload