问题 如何在模型中调用ApplicationController中定义的方法


我在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中工作。


8037
2018-04-17 12:11


起源

正如两个答案所说,你不应该从模型中调用控制器方法。不推荐。读入模型视图控制器(MVC)。保持独立。基本上模型与存储进行对话,控制器与模型进行对话(而不是相反),并查看与控制器的对话。 - Leo Correa
由于Rails设计,并且无法调用ApplicationController.helpers(现在),您必须在模型中使用dup-code def“重复自己”。一定要在这两个地方添加评论,所以如果你在一个地方改变它,你记得去另一个地方改变它。 - JosephK


答案:


你为什么需要这样的东西?模型不应该知道它的控制器。在这种情况下,重新设计系统可能更合适。

这是类似的链接 线


7
2018-04-17 12:14





作为设计选择,不建议您从模型中调用控制器助手。

您只需将所需的详细信息作为参数传递给模型方法即可。


def转移(active_gateway)
  active = active_gateway
结束

5
2018-04-17 12:14