【问题标题】:How to call methods defined in ApplicationController in models如何在模型中调用ApplicationController中定义的方法
【发布时间】: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


【解决方案1】:

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

这里是类似thread的链接。

【讨论】:

    【解决方案2】:

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

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

    def 传输(active_gateway) 活动 = 活动网关 结尾

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-28
      • 2018-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多