Can we call a Controller's method from a view

2019-01-13 12:07发布

Well, I know it should not be asked here, But I did not find a better place to get answer. This question was asked in a good company's interview.

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

I couldn't answer that question that time. Would you please help?

4条回答
再贱就再见
2楼-- · 2019-01-13 12:37

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 %>
查看更多
戒情不戒烟
3楼-- · 2019-01-13 12:44

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.

查看更多
干净又极端
4楼-- · 2019-01-13 12:46

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

查看更多
Fickle 薄情
5楼-- · 2019-01-13 12:53

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?

查看更多
登录 后发表回答