My setup: Rails 2.3.10, Ruby 1.8.7
I would like some feedback on where it is best to put logic code, and REST API, that touches multiple models in a single transaction. For example, a user needs to buy a product, it’ll involve
- Checks if he has sufficient money (user model)
- Check if the product is available (product model)
- Calculate shipping charge (zipcode, product models)
- Subtract money
- Update product availability count
- …
You get the general idea. Let’s say I need to provide a buy REST API, which controller should it go in? And where should the actual logic go? Should it be in the model associated with the controller? Appreciate any insights.
I don’t know what the convention is (if there is one), but I tend to do my multi-model transactions in a “noun-verb” format. For example, if a
Userwanted to purchase aProduct, I would do:The controller works similarly, although I usually think about it in passive voice (e.g., “what verb is being done to what noun”, rather than “what noun is doing what verb”. For example, if a
Productwas being purchased, it might be aPOSTto/products/1/purchase, with the following controller code:Using these “conventions”, I can easily locate the logic in my app by thinking about what verb is being done to what noun.