应用程序帮助程序方法是否可用于所有视图?

时间:2014-07-26 06:04:20

标签: ruby-on-rails ruby-on-rails-4.1

Rails 4.1
Ruby 2.0
Windows 8.1

在我的助手/ application_helper.rb中,我有:

def agents_and_ids_generator
    agents = Agent.all.order(:last)
    if agents
      agents_and_ids = [['','']]
      agents.each do |l|
        name = "#{l.first} #{l.last}"
        agents_and_ids << [name,l.id]
      end
      return agents_and_ids
    end
  end

在我的views / agents / form.html.erb中,我有以下内容:

<%= f.select :agent_id, options_for_select(agents_and_ids_generator) %>

在我的controllers / agents_controller.rb中,我有以下内容:

include ApplicationHelper

但是当我转到此视图时,我收到以下错误消息:

未定义的局部变量或方法`agents_and_ids_generator'用于#&lt;#:0x00000006fc9148&gt;

如果我将agents_and_ids_generator方法移动到helpers / agents_helper.rb,它可以正常工作。

我认为通过将方法放在应用程序帮助器中并将应用程序包含在控制器中,这些方法可用于视图。这个假设我不正确吗?

答案:

确保应用程序帮助程序未包含在控制器中,并添加了以下简化:

<%= 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
     "#{self.first} #{self.last}"
   end
end

2 个答案:

答案 0 :(得分:5)

<强>助手

底线答案是您的所有观看次数中均可使用application_helper

Rails实际上在整个地方使用帮助程序 - 从form_for到其他内置Rails方法的所有内容。

由于Rails基本上只是一系列的课程和模块,helpers在渲染视图时加载,允许您在需要时调用它们。 Controllers在堆栈中处理得更早,因此您必须明确包含所需的帮助程序

重要 - 您不需要在ApplicationHelper中加入ApplicationController应该正常工作


您的问题

可能存在导致问题的几种可能性;我有两个想法:

  
      
  1. 您的AgentsController是否继承自ApplicationController
  2.   
  3. 或许您加入ApplicationHelper会导致问题
  4.   

奇怪的是,AgentsHelper有效,ApplicationHelper没有。解释这一点的一种方法是Rails将根据正在操作的控制器加载一个帮助器,这意味着如果你不从ApplicationController,继承ApplicationHelper则不会被调用

您需要对此进行测试:

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

接下来,您需要摆脱控制器中的include ApplicationHelper。这只会使助手可用于该类(控制器),并且不会对您的视图产生任何影响

说完这个后,可能导致您的视图加载ApplicationHelper时出现问题 - 这意味着您一定要测试从ApplicationController

中删除它

方式

最后,使用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

答案 1 :(得分:1)

更新5条。我遇到了一个类似的问题,即视图未从application_helper.rb中获取方法。 This post帮助了我。新Rails应用程序的helpers目录中提供的文件仅适用于这些视图。 application_helper.rb中的方法并非对所有视图都自动可用。要创建可用于所有视图的辅助方法,请在诸如clean_emails_helper.rb之类的辅助目录中创建一个新的辅助文件,并在此处添加您的自定义方法,如下所示:

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

然后,您可以从应用程序中的任何视图调用<%= clean_email(email) %>