新しい連絡先を作成し、定義済みの色のセットから好きな色を尋ねるページがあるとします。コントローラーとビュー/テンプレートが続きます。
コントローラ
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' #
しかし、なぜこれが起こっているのかわかりません。誰かがこれに光を当てることができますか?