Rails: call another controller action from a controller

后端 未结 9 1007
眼角桃花
眼角桃花 2020-11-27 11:47

I need to call the create action in controller A, from controller B.

The reason is that I need to redirect differently when I\'m calling from controller B.

相关标签:
9条回答
  • 2020-11-27 12:17

    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)
    
    0 讨论(0)
  • 2020-11-27 12:19

    You can call another action inside a action as follows:

    redirect_to action: 'action_name'

    class MyController < ApplicationController
      def action1
       redirect_to action: 'action2'
      end
    
      def action2
      end
    end
    
    0 讨论(0)
  • 2020-11-27 12:27

    Composition to the rescue!

    Given the reason, rather than invoking actions across controllers one should design controllers to seperate shared and custom parts of the code. This will help to avoid both - code duplication and breaking MVC pattern.

    Although that can be done in a number of ways, using concerns (composition) is a good practice.

    # controllers/a_controller.rb
    class AController < ApplicationController
      include Createable
    
      private def redirect_url
        'one/url'
      end
    end
    
    # controllers/b_controller.rb
    class BController < ApplicationController
      include Createable
    
      private def redirect_url
        'another/url'
      end
    end
    
    # controllers/concerns/createable.rb
    module Createable
      def create
        do_usefull_things
        redirect_to redirect_url
      end
    end
    

    Hope that helps.

    0 讨论(0)
提交回复
热议问题