2017-03-01 20 views
0

我有我的set_pagination_header上應用控制器,我需要一些其他的控制器稱之爲:Rails:如何從控制器的before_action/after_action方法INLINE中調用ApplicationController方法WITH ARGS?

# syntax error in line below 
after_action :set_pagination_header, :my_argument_object, only: [:index] 

def index 
    @my_argument_object = Resource.page(1) 
    render json: @my_argument_object 
end 

我可以直接發送原始@my_argument_object,所以我不想做的事:

def set_pagination_header(name, options = {}) 
    scope = instance_variable_get("@#{name}") 
    # some_logic_here 
end 

1)什麼是正確的語法(需要一個內聯的)?

2)爲什麼不是set_pagination_header(object, options = {})是什麼定義?


編輯:我發現了一些here

after_filter only: [:index] { set_pagination_header(:germs) } 

它的老語法,我們得到了after_action現在。儘管如此,我相信有一個內聯方式來做到這一點,不是嗎?

# I tried and that didn't work 
after_action :set_pagination_header(:my_argument_object), only: [:index] 
after_action { :set_pagination_header(:my_argument_object) } only: [:index] 
after_action { :set_pagination_header, :my_argument_object } only: [:index] 

回答

0

內聯的方式,但不那麼幹淨!

after_action Proc.new{ set_pagination_header(:paged_orders) }, only: [:index] 
+0

,仍然沒有想出是否有可能發送哈希作爲!參數,而不僅僅是字符串名稱,它會讓我選擇使用該字符串的正確引用 –

0

你只需要一個方法調用添加到您的回調

after_action :set_pagination_header_callback, only: :index 

def set_pagination_header_callback 
    set_pagination_header(...your variables here...) 
end 

# application_controller.rb 
def set_pagination_header(name, options = {}) 
    scope = instance_variable_get("@#{name}") 
    # some_logic_here 
end 
+0

:(對不起,我期待一個內嵌的方式來做到這一點,只是做一個編輯的問題:忘記提到它,我的壞 –

相關問題