2012-04-17 38 views
10

我在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调用这个方法定义的方法模特ApplicationController中定义的方法。

所以我写了

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。

+2

正如两个答案所说,你不应该从你的模型调用控制器方法。不推荐。读入模型视图控制器(MVC)。保持独立。基本上模型与存储,控制器会谈模型(而不是反其道而行),并查看与控制器的谈话。 – 2012-04-17 12:21:37

+0

由于Rails设计,并且无法调用ApplicationController.helpers(现在),所以您必须在模型中使用重复代码def'重复自己'。一定要在这两个地方添加评论,所以如果你一次改变它,你会记得去另一个地方改变它。 – JosephK 2017-06-13 10:40:43

回答

6

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

这里有一个链接到类似的thread

5

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

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

 

def transfer(active_gateway) 
    active = active_gateway 
end