2015-02-11 87 views
1

我剛剛從PHP切換到軌道,我想弄清楚如何讓我的menu_price控制器從我的類別控制器訪問變量。從另一個控制器訪問變量

class CategoriesController < ApplicationController 
    before_action :set_category, only: [:show, :edit, :update, :destroy] 

    def index 
    @categories = Category.all 
    end 

我想到了全局變量,但是這不是一個安全的方法。我還讀到,紅寶石不支持多重繼承,這將成爲我的第二種方法。

這裏是我的菜單控制器(我只加它的一部分,因爲代碼的其餘部分是不相關的。)

class MenuPricesController < ApplicationController 
    before_action :set_menu_price, only: [:show, :edit, :update, :destroy] 

    def index 
    @menu_prices = MenuPrice.all 
    end 

我敢肯定,這是很簡單的,但我一直在尋找的過去一小時左右的答案。我閱讀了關於該文件夾的信息,但我不確定如何處理這個問題,在我的書中沒有那麼深入。

+0

這個帖子有一個很好的答案這個問題http://stackoverflow.com/questions/20591031/accessing-one-controller-variable-in-another-controller-in-rails/20591384#20591384 – Joel 2015-02-11 20:41:37

+1

你爲什麼需要從另一個控制器訪問變量?如果你需要'MenuPricesController'中的'Category',只需在@RailsOuter的回答中將其實例化。 雖然我必須承認這是一種代碼味道。我有一種直覺,認爲'Category'和'MenuPrice'應該在它們之間有聯繫。如果是這種情況,您只能根據需要獲取類別並獲取菜單價格。 – Ninjarabbi 2015-02-11 20:53:17

回答

1

在你MenuPricesController你可以創建一個新的Category實例,並使用它像這樣:

class MenuPricesController < ApplicationController 
    before_action :set_menu_price, only: [:show, :edit, :update, :destroy] 


def index 
    @menu_prices = MenuPrice.all 
    @categories = Category.all 
    # do something 
    end 
+0

謝謝我不知道爲什麼它沒有工作,我第一次嘗試這個 – 2015-02-12 01:27:50

1

Category.all未在CategoriesController類中定義的,它在Category類(我假設是ActiveModel模型...)你可以(也應該)在你的控制器動作中創建你的實例變量。