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

时间:2012-01-18 07:20:27

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1

在Rails MVC中,你可以从一个视图中调用一个控制器的方法(因为一个方法可以被调用来自一个帮助器)?如果是,怎么样?

4 个答案:

答案 0 :(得分:130)

以下是答案:

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

然后,在您看来,您可以在ERB中引用它与<%<%=完全相同的方式:

<% my_method %>

答案 1 :(得分:23)

您可能希望将方法声明为“helper_method”,或者将其移动到帮助器。

What do helper and helper_method do?

答案 2 :(得分:10)

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

@controller.public_method

和私人方法:

@controller.send("private_method", args)

查看更多详情here

答案 3 :(得分: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

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

 class ApplicationController < ActionController::Base
   helper :all

   def foo
    # your foo logic
   end

   def bar
    # your bar logic
   end
 end

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