Ruby On Rails, Design, Simplicity, Web 2.0, Ajax, Mac and Tons of Pizza.

Oct 25

How to call a controller's action from a different controller

Posted by Sandro Paganotti in 2 comments digg this add to delicious

We come up with this solution after a couple of failing attempt to find a way to emulate a redirect_to method without actually create a 302 HTTP message which need to be sent to the user and then back to the application.

By using this internal_redirect_to function you will be able to get the same results as a normal redirect_to without send anything to the user, only keep in mind to explicit invoke the return after this function.


def internal_redirect_to (options={})
    params.merge!(options)
    (c = ActionController.const_get(Inflector.classify("#{params[:controller]}_controller")).new).process(request,response)
    c.instance_variables.each{|v| self.instance_variable_set(v,c.instance_variable_get(v))} 
end

Note: this function must be placed inside the calling controller.

Then you can simply invoke this function by typing:


MasterController < ApplicationController
  def index
    internal_redirect_to :controller=>'another', :action=>'an_action'
   return 
  end
end

Sandro

Comments

  • Igor Petrushenko

    Posted on November 21

    Very nice, thanks! Igor, http://www.MyTaskHelper.com
  • konya turkey map

    Posted on December 14

    I Wanted To say Thanks Guys

Post a comment

Categories:

Tags:

Powered by Mephisto, Valid XHTML 1.1, Valid CSS - Supported by Wave Factory