I'd like to be able to dispatch from one controller action to another conditionally, based on a combination of query parameters and data in the database.
What I have right now is something like:
class OldController < ApplicationController
def old_controller_action
if should_use_new_controller
new_params = params.dup
new_params[:controller] = "new_controller_action"
redirect_to new_params
return
end
# rest of old and busted
end
end
class NewController < ApplicationController
def new_controller_action
# new hotness
end
end
This works just fine, but it issues an HTTP redirect, which is slow. I'd like to be able to do this same thing, but within the same HTTP request.
Is there a clean way to do this?
Edit: The bounty will go to someone who can show me a clean way to do this that leaves the controllers and their actions relatively untouched (other than the redirect code itself).
Every controller can have a default action method as per the configured route in the RouteConfig class. By default, the Index () method is a default action method for any controller, as per configured default root, as shown below. However, you can change the default action name as per your requirement in the RouteConfig class.
As mentioned above, name of the action methods in the Web API controller plays an important role. Action method name can be the same as HTTP verbs like Get, Post, Put, Patch or Delete as shown in the Web API Controller example above.
All the public methods of the Controller class are called Action methods. They are like any other normal methods with the following restrictions: Action method must be public. It cannot be private or protected Action method cannot be a static method.
All the public methods of a Controller class are called Action methods. They are like any other normal methods with the following restrictions: Action method must be public. It cannot be private or protected. Action method cannot be overloaded. Action method cannot be a static method.
Instead of calling code across actions, extract the code to lib/ or something, and call that code from both controllers.
# lib/foo.rb
module Foo
def self.bar
# ...
end
end
# posts_controller
def index
Foo.bar
end
# things_controller
def index
Foo.bar
end
Create an instance of the controller class:
@my_other_controller = MyOtherController.new
Then call methods on it:
@my_other_controller.some_method(params[:id])
I prefer the module idea, but this should do the trick.
You can also pass parameters as a whole from another controller:
@my_other_controller.params = params
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With