我们可以从视图中调用Controller的方法(理想情况下我们从helper调用)吗?

Man*_*ava 60 ruby ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

嗯,我知道不应该在这里问,但我没有找到一个更好的地方来得到答案.这个问题在一家好公司的采访中被问到了.

在Rails MVC中,你能从一个视图调用一个控制器的方法(理想情况下我们从helper调用)吗?如果有,怎么样?

那个时候我无法回答那个问题.你能帮忙吗?

sai*_*lor 140

这是答案:

class MyController < ApplicationController
  def my_method
    # Lots of stuff
  end
  helper_method :my_method
end
Run Code Online (Sandbox Code Playgroud)

然后,在您的视图中,您可以在ERB中引用它与您期望的完全相同<%<%=:

<% my_method %>
Run Code Online (Sandbox Code Playgroud)


Pav*_*ing 23

您可能希望将方法声明为"helper_method",或者将其移动到帮助程序.

helper和helper_method做了什么?


Wah*_*Ali 10

从来没有尝试过,但调用公共方法类似于:

@controller.public_method
Run Code Online (Sandbox Code Playgroud)

和私人方法:

@controller.send("private_method", args)
Run Code Online (Sandbox Code Playgroud)

在这里查看更多细节


prz*_*adu 6

使用动作辅助方法 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
Run Code Online (Sandbox Code Playgroud)

或者您也可以使用以下方法将所有操作作为助手方法: helper :all

 class ApplicationController < ActionController::Base
   helper :all

   def foo
    # your foo logic
   end

   def bar
    # your bar logic
   end
 end
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,您都可以从所有控制器访问foo和bar.