70

In Rails MVC, can you call a controller's method from a view (as a method could be called call from a helper)? If yes, how?

Jon Schneider
  • 21,628
  • 17
  • 129
  • 157
Manish Shrivastava
  • 26,075
  • 13
  • 88
  • 100

4 Answers4

153

Here is the answer:

class MyController < ApplicationController
  def my_method
    # Lots of stuff
  end
  helper_method :my_method
end

Then, in your view, you can reference it in ERB exactly how you expect with <% or <%=:

<% my_method %>
Hawkins
  • 631
  • 6
  • 21
sailor
  • 7,218
  • 3
  • 22
  • 33
24

You possibly want to declare your method as a "helper_method", or alternatively move it to a helper.

What do helper and helper_method do?

Community
  • 1
  • 1
Pavling
  • 3,853
  • 1
  • 20
  • 25
10

Haven't ever tried this, but calling public methods is similar to:

@controller.public_method

and private methods:

@controller.send("private_method", args)

See more details here

Taryn
  • 224,125
  • 52
  • 341
  • 389
Wahaj Ali
  • 3,960
  • 2
  • 19
  • 34
9

make your action helper method using helper_method :your_action_name

class ApplicationController < ActionController::Base
  def foo
    # your foo logic
  end
  helper_method :foo

  def bar
    # your bar logic
  end
  helper_method :bar
end

Or you can also make all actions as your helper method using: helper :all

 class ApplicationController < ActionController::Base
   helper :all

   def foo
    # your foo logic
   end

   def bar
    # your bar logic
   end
 end

In both cases, you can access foo and bar from all controllers.

przbadu
  • 5,093
  • 2
  • 37
  • 54