如何调用模型ApplicationController中定义的方法(How to call meth

2019-06-23 17:29发布

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

Answer 1:

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

下面是类似的链接线 。



Answer 2:

作为一个设计选择,它不建议从模型呼叫控制器助手。

您只需简单地传递所需的细节到模型方法作为参数。


def transfer(active_gateway)
  active = active_gateway
end


文章来源: How to call methods defined in ApplicationController in models