3

I need to call methods from another controller. What is the best way? For example:

catalogues_controller.rb

class Site::CataloguesController < ApplicationController
  respond_to :js, :html

  def index
    produc_list # call method other controller
  end
end

other_controller.rb

class OtherController < ApplicationController

  respond_to :js, :html

  def produc_list
     myObj = Catalagues.find(params[:id])
     render :json => myObj
  end
end
Mischa
  • 42,876
  • 8
  • 99
  • 111
Camilo.Orozco
  • 287
  • 2
  • 4
  • 15
  • 6
    inheritance, common module.. – apneadiving Feb 20 '13 at 15:19
  • 2
    thanks, please provide a example , i'm new in ruby ... thanks – Camilo.Orozco Feb 20 '13 at 15:21
  • 1
    A similar question was asked here http://stackoverflow.com/questions/128450/best-practices-for-reusing-code-between-controllers-in-ruby-on-rails for creating modules checkout http://stackoverflow.com/questions/4906932/how-to-create-and-use-a-module-using-ruby-on-rails-3 – Noz Feb 20 '13 at 15:31
  • Inheritance means, you could put your common method in ApplicationController (both inherit from there) and call it from OtherController and Site::CataloguesController. Of course you could use a more specific parent for both controllers if they share other things in common. – Leonel Galán Feb 20 '13 at 15:36

3 Answers3

10

You could implement a module, and include it in your Controller.

Let's call this module "Products Helper":

# In your app/helpers
# create a file products_helper.rb
module ProductsHelper

  def products_list(product_id)
    catalague = Catalagues.where(id: product_id).first
    render :json => catalague
  end

end

And then, in the controllers you need to use this method:

class Site::CataloguesController < ApplicationController
  include ProductsHelper

  respond_to :js, :html

  def index
    products_list(your_id) # replace your_id with the corresponding variable
  end
end
MrYoshiji
  • 54,334
  • 13
  • 124
  • 117
3

You can call dispatch directly on your controller's method. Pass in an ActionDispatch::Response instance and it will be populated with the response. Assuming a json response in this example:

def other_controller_method
  req = ActionDispatch::Request.new(request.env)
  resp = ActionDispatch::Response.new
  YourControllerClass.dispatch(:your_controller_method_name, req, resp)
  render json: resp.body, status: resp.status
end
mgauthier
  • 321
  • 2
  • 6
1

If you have RESTful routes (and acccess to the helper methods that come with them), then you should just be able to use redirect_to to redirect to whatever action you want to call,

#  something like... controller_name_action_name_url 

#  In your case, in the catalouges/index method
#  Note this also assumes your controller is named 'other'
   redirect_to others_product_list_url(product_id)
ply
  • 1,141
  • 1
  • 10
  • 17