【发布时间】:2012-04-17 12:11:50
【问题描述】:
我在 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。
所以我写了
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)。让事情保持独立。基本上模型与存储对话,控制器与模型对话(而不是相反),视图与控制器对话。
-
由于 Rails 设计,并且移除了调用 ApplicationController.helpers 的能力(现在),您必须在模型中使用 dup-code def 来“重复自己”。一定要在这两个地方添加评论,所以如果你在一个地方改变它,你记得去另一个地方改变它。
标签: ruby-on-rails ruby ruby-on-rails-3.2