2013-02-20 9 views
3

다른 컨트롤러에서 메서드를 호출해야합니다. 가장 좋은 방법은 무엇입니까? 당신은 모듈을 구현하고 그것은 당신의 컨트롤러에 포함 할 수다른 컨트롤러의 메서드를 호출하는 방법

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

    def index 
    produc_list # call method other controller 
    end 
end 

class OtherController < ApplicationController 

    respond_to :js, :html 

    def produc_list 
    myObj = Catalagues.find(params[:id]) 
    render :json => myObj 
    end 
end 
+6

상속, 공통 모듈 ... – apneadiving

+2

감사 할 경우는 예를 제공하시기 바랍니다, 내가 ... 덕분에 루비의 새로운이야 –

+1

비슷한 질문은 여기에 http 질문을 받았다 : // 유래 .com/questions/128450/모듈을 생성하기위한 루비 온 레일 러 사이의 코드 재사용을위한 베스트 프랙티스 http://stackoverflow.com/questions/4906932/how-to-create- and-use-a-module-using-ruby-on-rails-3 – Noz

답변

10

other_controller.rb

catalogues_controller.rb 예를 들면 다음과 같습니다. 당신이에 편안하고 경로 (및 acccess가있는 경우

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 
+1

죄송합니다. app/helpers 폴더는 컨트롤러가 아닌보기에 헬퍼를 넣는 데 사용됩니다. – karlihnos

1

: 컨트롤러에이 방법을 사용할 필요가 다음

# 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 

그리고 :

의이 모듈 "제품 도우미"를 부르 자 도우미 메서드가있는 경우), 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) 
2

컨트롤러의 방법으로 직접 디스패치를 ​​호출 할 수 있습니다. 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 
관련 문제