如何调用另一个控制器的方法

Cam*_*zco 3 ruby-on-rails ruby-on-rails-3

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

catalogues_controller.rb

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

  def index
    produc_list # call method other controller
  end
end
Run Code Online (Sandbox Code Playgroud)

other_controller.rb

class OtherController < ApplicationController

  respond_to :js, :html

  def produc_list
     myObj = Catalagues.find(params[:id])
     render :json => myObj
  end
end
Run Code Online (Sandbox Code Playgroud)

MrY*_*iji 10

您可以实现一个模块,并将其包含在Controller中.

我们称这个模块为"产品助手":

# 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
Run Code Online (Sandbox Code Playgroud)

然后,在控制器中,您需要使用此方法:

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
Run Code Online (Sandbox Code Playgroud)