How to call methods defined in ApplicationController in models

谁说胖子不能爱 提交于 2019-12-01 00:01:00

问题


I have defined method in ApplicationController

class ApplicationController < ActionController::Base
   helper_method :get_active_gateway
   def get_active_gateway(cart)
     cart.account.gateways
   end
end

When I am calling this method in model

class Order < ActiveRecord::Base
   def transfer
     active= get_active_gateway(self.cart)
   end
end

It throwing error undefined local variable get_active_gateway.

So I wrote

class Order < ActiveRecord::Base
   def transfer
    active= ApplicationContoller.helpers.get_active_gateway(self.cart)
   end
end

Then it was throwing error undefined method nil for Nilclass.

I am working in Rails 3.2.0.


回答1:


Why would you need such thing? The model should not know about its controllers. Maybe a redesign of your system will be more appropriate in this case.

Here is a link to similar thread.




回答2:


As a design choice, its not recommended to call controller helpers from your models.

You can just simply pass the required details to your model methods as arguments.


def transfer(active_gateway)
  active = active_gateway
end


来源:https://stackoverflow.com/questions/10190995/how-to-call-methods-defined-in-applicationcontroller-in-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!