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

问题描述 投票:55回答:4

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

ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1
4个回答
134
投票

这是答案:

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

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

<% my_method %>

23
投票

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

What do helper and helper_method do?


10
投票

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

@controller.public_method

和私人方法:

@controller.send("private_method", args)

查看更多详情here


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。

© www.soinside.com 2019 - 2024. All rights reserved.