在哪里为Rails控制器放置Ruby辅助方法?

at.*_*at. 68 ruby ruby-on-rails view-helpers ruby-on-rails-3 ruby-on-rails-3.2

我有一些(或所有)控制器需要的Ruby方法.我试过把它们放进去/app/helpers/application_helper.rb.我已经将它用于视图中使用的方法.但是控制器看不到那些方法.是否有其他地方我应该放他们或我需要以不同方式访问这些帮助方法?

使用最新的稳定Rai​​ls.

Rya*_*igg 72

你应该在里面定义方法ApplicationController.

  • 他还必须在`ApplicationController`中添加`helper_method:my_helper_method`,以使它们可供视图使用. (25认同)
  • 随着时间的推移,这不会导致肥胖的控制器吗? (2认同)
  • 还有 @David 违反了 MVC (2认同)

Joh*_*ary 60

For Rails 4 onwards, concerns are the way to go. There is a decent article here http://richonrails.com/articles/rails-4-code-concerns-in-active-record-models

In essence, if you look in your controllers folder you should see a concerns sub-folder. Create a module in there along these lines

module EventsHelper
  def do_something
  end
end
Run Code Online (Sandbox Code Playgroud)

Then, in the controller just include it

class BadgeController < ApplicationController
  include EventsHelper

  ...
end
Run Code Online (Sandbox Code Playgroud)

  • 当您不需要所有控制器中包含的辅助方法时,我发现这是最好的解决方案.该解决方案也适用于模型. (2认同)

Muh*_*ais 29

你应该在应用程序控制器中定义方法,如果你有很少的方法,那么你可以这样做

class ApplicationController < ActionController::Base    
  helper_method :first_method
  helper_method :second_method

  def first_method
    ... #your code
  end

  def second_method
    ... #your code
  end
end
Run Code Online (Sandbox Code Playgroud)

您还可以包含帮助文件,如下所示

class YourController < ApplicationController
  include OneHelper
  include TwoHelper
end
Run Code Online (Sandbox Code Playgroud)


Dav*_*vid 15

您可以使用view_context,例如,从控制器调用任何帮助方法

view_context.my_helper_method
Run Code Online (Sandbox Code Playgroud)


hyp*_*jas 8

Ryan Bigg的反应很好.

其他可能的解决方案是向控制器添加帮助程序:

class YourController < ApplicationController
  include OneHelper
  include TwoHelper
 end
Run Code Online (Sandbox Code Playgroud)

最好的祝福!