我在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。
正如兩個答案所說,你不應該從你的模型調用控制器方法。不推薦。讀入模型視圖控制器(MVC)。保持獨立。基本上模型與存儲,控制器會談模型(而不是反其道而行),並查看與控制器的談話。 – 2012-04-17 12:21:37
由於Rails設計,並且無法調用ApplicationController.helpers(現在),所以您必須在模型中使用重複代碼def'重複自己'。一定要在這兩個地方添加評論,所以如果你一次改變它,你會記得去另一個地方改變它。 – JosephK 2017-06-13 10:40:43