3

我需要从另一个控制器调用方法。什么是最好的方法?例如:

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
4

3 回答 3

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
于 2013-02-20T15:53:01.520 回答
3

您可以直接在控制器的方法上调用调度。传入一个 ActionDispatch::Response 实例,它将填充响应。假设在此示例中为 json 响应:

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
于 2016-11-08T08:20:37.343 回答
1

如果您有 RESTful 路由(并且可以访问它们附带的辅助方法),那么您应该能够使用 redirect_to 重定向到您想要调用的任何操作,

#  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)
于 2013-02-20T15:53:38.873 回答