Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: call another controller action from a controller

People also ask

Can a controller call another controller?

Yes, you can call a method of another controller. The controller is also a simple class. Only things are that its inheriting Controller Class. You can create an object of the controller, but it will not work for Routing if you want to redirect to another page.

Can we call controller method in model Rails?

As the two answers said, you should not be calling controller methods from your models. It is not recommended.

What is action controller Rails?

Action Controllers are the core of a web request in Rails. They are made up of one or more actions that are executed on request and then either it renders a template or redirects to another action.


You can use a redirect to that action :

redirect_to your_controller_action_url

More on : Rails Guide

To just render the new action :

redirect_to your_controller_action_url and return

To use one controller from another, do this:

def action_that_calls_one_from_another_controller
  controller_you_want = ControllerYouWant.new
  controller_you_want.request = request
  controller_you_want.response = response
  controller_you_want.action_you_want
end

The logic you present is not MVC, then not Rails, compatible.

  • A controller renders a view or redirect

  • A method executes code

From these considerations, I advise you to create methods in your controller and call them from your action.

Example:

 def index
   get_variable
 end

 private

 def get_variable
   @var = Var.all
 end

That said you can do exactly the same through different controllers and summon a method from controller A while you are in controller B.

Vocabulary is extremely important that's why I insist much.


You can use url_for to get the URL for a controller and action and then use redirect_to to go to that URL.

redirect_to url_for(:controller => :controller_name, :action => :action_name)

This is bad practice to call another controller action.

You should

  1. duplicate this action in your controller B, or
  2. wrap it as a model method, that will be shared to all controllers, or
  3. you can extend this action in controller A.

My opinion:

  1. First approach is not DRY but it is still better than calling for another action.
  2. Second approach is good and flexible.
  3. Third approach is what I used to do often. So I'll show little example.

    def create
      @my_obj = MyModel.new(params[:my_model])
      if @my_obj.save
        redirect_to params[:redirect_to] || some_default_path
       end
    end
    

So you can send to this action redirect_to param, which can be any path you want.