13

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.

Shiko
  • 2,448
  • 1
  • 24
  • 31
Beena Shetty
  • 3,676
  • 2
  • 28
  • 31
  • 2
    As the two answers said, you should not be calling controller methods from your models. It is not recommended. Read into Model View Controller (MVC). To keep things independent. Basically Model talks to storage, controller talks to model (not the other way around), and view talks to controller. – Leo Correa Apr 17 '12 at 12:21
  • Due to Rails design, and removing the ability to call ApplicationController.helpers (now), you must 'repeat yourself' with a dup-code def in the model. Be sure to add a comment in both places so if you change it in once place, you remember to go and change it in the other. – JosephK Jun 13 '17 at 10:40

2 Answers2

8

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.

Community
  • 1
  • 1
Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135
5

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
Rishav Rastogi
  • 15,484
  • 3
  • 42
  • 47