0
假設我有一個頁面創建一個新的聯繫人,並從一組預定義的顏色中詢問他們喜歡什麼顏色。控制器和視圖/模板如下。從散列模型導軌simple_form
控制器
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]
)。然而,當我運行它,我得到以下錯誤:
undefined method `selected_colors' for #
但我不明白爲什麼會這樣,有人可以提供一些線索這光?
工作。 Ruby/Rails是一個神祕的野獸。謝謝。 –