【发布时间】:2014-09-18 00:53:26
【问题描述】:
Rails 4.1
Ruby 2.0
Windows 8.1
在我的 helpers/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
在我的视图/代理/form.html.erb 中,我有以下内容:
<%= f.select :agent_id, options_for_select(agents_and_ids_generator) %>
在我的控制器/agents_controller.rb 中,我有以下内容:
include ApplicationHelper
但是当我转到这个视图时,我收到以下错误消息:
# 的未定义局部变量或方法 `agents_and_ids_generator'
如果我将 agent_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
【问题讨论】:
-
你不必在你的控制器中
include ApplicationHelper -
是的,但这并不能解释我要问的问题
标签: ruby-on-rails ruby-on-rails-4.1