Where are Rails helpers available?

坚强是说给别人听的谎言 提交于 2020-06-25 18:43:10

问题


I'm referring to the modules you create in app/helpers. Are they available in:

  • Views?
  • Controllers?
  • Models?
  • Tests?
  • Other files?
  • Sometimes?
  • All the time?

回答1:


In Rails 5 all Helpers are available to all Views and all Controllers, and to nothing else.

http://api.rubyonrails.org/classes/ActionController/Helpers.html

These helpers are available to all templates by default.

By default, each controller will include all helpers.

In Views you can access helpers directly:

module UserHelper
  def fullname(user)
    ...
  end
end

# app/views/items/show.html.erb
...
User: <%= fullname(@user) %>
...

In Controllers you need the #helpers method to access them:

# app/controllers/items_controller.rb
class ItemsController
  def show
    ...
    @user_fullname = helpers.fullname(@user)
    ...
  end
end

You can still make use of helper modules in other classes by includeing them.

# some/other/klass.rb
class Klass
  include UserHelper
end

The old behavior was that all helpers were included in all views and just each helper was included in the matching controller, eg. UserHelper would only be included in UserController.

To return to this behavior you can set config.action_controller.include_all_helpers = false in your config/application.rb file.



来源:https://stackoverflow.com/questions/43431955/where-are-rails-helpers-available

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!