Rails: How do I POST inside another controller action?

It will sound strange, but listen to me ... I need to make the equivalent of a POST request to one of my other controllers. SimpleController is a simplified version of a more detailed controller. How can I do this properly?

 class VerboseController < ApplicationController def create # lots of required params end end class SimpleController < ApplicationController def create # prepare the params required for VerboseController.create # now call the VerboseController.create with the new params end end 

Maybe I'm thinking too much about it, but I don’t know how to do it.

+6
source share
2 answers

Communication between controllers in a Rails application (or any web application using the same adapter model template) is something you should avoid. When you are tempted to do this, consider it a sign that you are struggling with the patterns and frameworks on which your application is built, and that you rely on logic, implemented at the wrong level of your application.

As @ismaelga explained in a comment; both controllers must invoke some common component to control this common behavior and keep your controllers skinny. In Rails, which is often a method on a model object, especially for the type of creation behavior, you seem to be worried in this case.

+7
source

You must not do this. Are you creating a model? Then using two class methods on the model would be much better. It also greatly improves the code. Then you can use the methods not only in the controllers, but also in the background (etc.) in the future.

For example, if you create Person:

 class VerboseController < ApplicationController def create Person.verbose_create(params) end end class SimpleController < ApplicationController def create Person.simple_create(params) end end 

Then in the Person model you can do the following:

 class Person def self.verbose_create(options) # ... do the creating stuff here end def self.simple_create(options) # Prepare the options as you were trying to do in the controller... prepared_options = options.merge(some: "option") # ... and pass them to the verbose_create method verbose_create(prepared_options) end end 

Hope this helps a little. :-)

+3
source

Source: https://habr.com/ru/post/915740/


All Articles