I would like to call a TestController#actiona from another ResultController#actionb passing the parameters for the actiona along with the call in rails.
Does anyone know what the most efficient way to achieve this is?
I have tried just calling the method like the code below but getting an error. What am I doing wrong?
Sample Pseudocode:
class TestController < ApplicationController
def actiona
# @value = do_something_with(params) // we are doing something with params
# render resource: @value, status: 201
end
end
class ResultController < ApplicationController
def actionb
# new_params = params + some_other_things // building new params
# @new_value = TestController.new.actiona(new_params) // we are passing the new_params
# render resource: @new_value, status: 201
end
end
I expect that a call to the ResultController#actionb calls the TestController#actiona with the params and renders the same @value that TestController#actiona would have returned if we called it directly.
actiona is an instance method. You can't call actiona on the class TestController.
Furthermore, if it would work, you will execute both call to render, from actiona and from actionb which make no sense. A call to a controller action must call render only once.
If you want to execute the actiona from the actionb, you can trigger a redirection using redirect_to with your params.
If you just want to render the view of the TestController, from the actionb, you can specify the expected view when using render method.
If you just want to reuse some code, you can extract that part of the code into a concern.