Can we call a Controller's method from a view (as we call from helper ideally)?

こ雲淡風輕ζ 提交于 2019-11-27 07:10:52
sailor

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 %>
Pavling

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?

Wahaj Ali

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

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.

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