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

13

我在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

我遇到了一个问题,错误提示为 undefined method nil for Nilclass

我正在使用Rails 3.2.0。


2
正如其他两个答案所说,您不应该从模型中调用控制器方法。这是不建议的。了解一下模型视图控制器(MVC)模式以保持独立性。基本上,模型与存储交互,控制器与模型交互(而非反向),视图与控制器交互。 - Leo Correa
由于Rails的设计,现在无法调用ApplicationController.helpers,因此您必须在模型中使用dup-code def来“重复自己”。请确保在两个位置都添加注释,以便如果您在一个地方进行更改,则记得去另一个地方进行更改。 - JosephK
2个回答

8

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

这里有一个类似的线程链接。


5

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

你可以将所需的详细信息作为参数简单地传递给模型方法。

def transfer(active_gateway)
  active = active_gateway
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接