假设我有一个页面,它创建一个新联系人并询问他们喜欢一组预定义颜色中的哪些颜色。控制器和视图/模板如下。
控制器
class ContactController < ApplicationController
class Color
attr_accessor :name, :hex
def initialize(attributes = {})
attributes.each do |n, v|
send("#{n}=", v)
end
end
end
def initialize
super
@colors = [
Color.new(:name => "Red", :hex => "#ff0000"),
Color.new(:name => "Green", :hex => "#00ff00"),
Color.new(:name => "Blue", :hex => "#0000ff")
]
end
def new
@contact = {
:contact_info => Contact.new, #first_name, last_name, email, etc.
:selected_colors => Array.new
}
end
end
查看/模板
<%= simple_form_for @contact, :as => "contact" ... do |f| %>
<%= f.simple_fields_for :contact_info do |cf| %>
<%= cf.input :first_name, :label => "First Name:" %>
<%= cf.input :last_name, :label => "Last Name:" %>
<%= cf.input :email, :label => "Email:" %>
<% end %>
<%= f.input :selected_colors, :collection => @colors, :as => :check_boxes, :label => "Which colors do you like?:" %>
<button type="submit">Volunteer!</button>
<% end %>
我正在构建一个散列以用作模型,并在表单回发时为所选颜色提供一个位置(contact[selected_colors]
)。但是,当我运行它时,我收到以下错误:
未定义的方法 `selected_colors' 用于#
但是我不明白为什么会发生这种情况,有人可以对此有所了解吗?