Rails: How to POST internally to another controller action?

前端 未结 2 1432
南旧
南旧 2020-12-17 02:29

This is going to sound strange, but hear me out...I need to be able to make the equivalent of a POST request to one of my other controllers. The SimpleController

2条回答
  •  臣服心动
    2020-12-17 02:57

    You shouldn't be doing this. Are you creating a model? Then having two class methods on the model would be much better. It also separates the code much better. Then you can use the methods not only in controllers but also background jobs (etc.) in the future.

    For example if you're creating a 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 could go like this:

    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
    

    I hope this can help a little. :-)

提交回复
热议问题