Are application helper methods available to all views?

眉间皱痕 提交于 2019-12-05 17:31:33

Helpers

The bottom line answer is the application_helper is available in all your views.

Rails actually uses helpers all over the place - in everything from the likes of form_for to other built-in Rails methods.

As Rails is basically just a series of classes & modules, the helpers are loaded when your views are rendered, allowing you to call them whenever you need. Controllers are processed much earlier in the stack, and thus you have to explicitly include the helpers you need in them

Important - you don't need to include the ApplicationHelper in your ApplicationController. It should just work


Your Issue

There may be several potentialities causing the problem; I have two ideas for you:

  1. Is your AgentsController inheriting from ApplicationController?
  2. Perhaps your inclusion of ApplicationHelper is causing an issue

Its strange that your AgentsHelper works, and ApplicationHelper does not. One way to explain this would be that Rails will load a helper depending on the controller which is being operated, meaning if you don't inherit from ApplicationController, the ApplicationHelper won't be called.

You'll need to test with this:

#app/controllers/application_controller.rb
Class AgentsController < ApplicationController
   ...
end

Next, you need to get rid of the include ApplicationHelper in your controller. This only makes the helper available for that class (the controller), and will not have any bearing on your view

Having said this, it may be causing a problem with your view loading the ApplicationHelper - meaning you should definitely test removing it from your ApplicationController


Method

Finally, your method could be simplified massively, using collection_select:

<%= f.collection_select :agent_id, Agent.all.order(:last), :id, :name_with_initial, prompt: true %>

#app/models/agent.rb
Class Agent < ActiveRecord::Base
   def name_with_initial
       "#{l.first} #{l.last}"
   end
end

Rails 5 update. I ran into a similar issue with views not picking up a method from application_helper.rb. This post helped me. The files that are provided in the helpers directory of a new rails app are for those views only. Methods in the application_helper.rb will not be available automatically to all views. To create a helper method that is available to all views, create a new helper file in the helper directory such as clean_emails_helper.rb and add your custom method here like this:

Module CleanEmailsHelper
  def clean_email(email)
     *do some stuff to email*
     return email
  end
end

Then you can call <%= clean_email(email) %> from any view in your app.

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