Adam Thompson
Adam Thompson

Reputation: 3506

Where to put create model and association logic in Rails?

I have a model A with some association to B via a join table AB. In the create action for the A controller I create the join model if the optional params are present for the association, otherwise only A is created without the AB association.

If I leave all the logic in the controller then the controller gets pretty fat and a pain to test and the logic cannot be re-used easily. If I try to move the logic to the model A then I just have a random method for create_with_AB or something similar. It doesn't feel right.

It feels like there should be some layer in between? I'm not sure if there is a common pattern used to handle a situation like this?

Upvotes: 1

Views: 304

Answers (1)

tejasbubane
tejasbubane

Reputation: 942

Your example does not seem very complex and can be done using nested attributes as mentioned in the comment. For more complex stuff, there is nothing provided by the framework and you have to come up with your own abstraction.

Have a look at service objects:

  1. https://www.engineyard.com/blog/keeping-your-rails-controllers-dry-with-services
  2. https://medium.com/selleo/essential-rubyonrails-patterns-part-1-service-objects-1af9f9573ca1

Again since these are community abstractions, there is no standard way of implementing service objects - some people use classes with call method, some use modules, etc. How you use them depends on your definition of clean code.

Upvotes: 4

Related Questions