2012-02-17 45 views
11

我有一個定義了兩個動作的軌道控制器:indexshow。 我有一個在index操作中定義的實例變量。該代碼是類似下面的東西:控制器所有動作的實例變量相同

def index 
    @some_instance_variable = foo 
end 

def show 
    # some code 
end 

我如何可以訪問@some_instance_variableshow.html.erb模板?

回答

10

除非您正在從index動作渲染show.html.erb,否則您還需要在show動作中設置@some_instance_variable。調用控制器操作時,它會調用匹配方法 - 因此在使用show操作時將不會調用index方法的內容。

如果需要@some_instance_variable設置爲同樣的事情在indexshow行動都,正確的方法是定義的另一種方法,雙方indexshow調用,用於設置實例變量。

def index 
    set_up_instance_variable 
end 

def show 
    set_up_instance_variable 
end 

private 

def set_up_instance_variable 
    @some_instance_variable = foo 
end 

使得set_up_instance_variable方法私人防止它被稱爲一個控制器動作,如果你有通配符路由(即match ':controller(/:action(/:id(.:format)))'

+1

謝謝@Emily。但是有沒有幹這種做法? – Red 2016-02-12 07:58:15

+0

謝謝@埃米爾我正在尋找同樣的東西。乾杯! – Aashish 2017-04-24 09:27:20

+0

只需將'before_action:set_up_instance_variable,僅:[:show,:index]'添加到控制器。這將在您指定的任何操作之前運行'set_up_instance_variable'。 – domi91c 2017-07-20 20:16:16

52

您可以通過過濾器之前使用定義多個操作實例變量,例如:

class FooController < ApplicationController 
    before_filter :common_content, :only => [:index, :show] 

    def common_content 
    @some_instance_variable = :foo 
    end 
end 

現在@some_instance_variable會從indexshow行動渲染的所有模板(包括諧音)訪問。

+4

這是一個更好的答案! – 2012-07-29 22:57:02

+0

非常乾燥。太好了! – Red 2016-02-12 08:27:44

+0

@Mori您將如何決定是否將方法/對象置於私人或受保護的或公共空間? THKS! – Red 2016-02-12 08:29:08

相關問題