2012-04-17 36 views
10

我在ApplicationController中如何調用

class ApplicationController < ActionController::Base 
    helper_method :get_active_gateway 
    def get_active_gateway(cart) 
    cart.account.gateways 
    end 
end 

當我在模型

class Order < ActiveRecord::Base 
    def transfer 
    active= get_active_gateway(self.cart) 
    end 
end 

它扔錯誤undefined local variable get_active_gateway調用這個方法定義的方法模特ApplicationController中定義的方法。

所以我寫了

class Order < ActiveRecord::Base 
    def transfer 
    active= ApplicationContoller.helpers.get_active_gateway(self.cart) 
    end 
end 

然後把它扔error undefined method nil for Nilclass

我正在使用Rails 3.2.0。

+2

正如兩個答案所說,你不應該從你的模型調用控制器方法。不推薦。讀入模型視圖控制器(MVC)。保持獨立。基本上模型與存儲,控制器會談模型(而不是反其道而行),並查看與控制器的談話。 – 2012-04-17 12:21:37

+0

由於Rails設計,並且無法調用ApplicationController.helpers(現在),所以您必須在模型中使用重複代碼def'重複自己'。一定要在這兩個地方添加評論,所以如果你一次改變它,你會記得去另一個地方改變它。 – JosephK 2017-06-13 10:40:43

回答

6

爲什麼你需要這樣的事情?該模型不應該知道它的控制器。在這種情況下,重新設計系統可能更合適。

這裏有一個鏈接到類似的thread

5

作爲設計選擇,不建議從模型中調用控制器助手。

只需將所需的詳細信息作爲參數傳遞給模型方法即可。

 

def transfer(active_gateway) 
    active = active_gateway 
end