Josh M.
Josh M.

Reputation: 27791

Rails simple_form from hash model

Suppose I have a page that creates a new contact and asks them what colors they like from a set of predefined colors. The controller and view/template follow.

Controller

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

View/Template

<%= 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 %>

I'm building a hash to use as the model and providing a place for the selected colors to go when the form is posted back (contact[selected_colors]). However, when I run this, I get the following error:

undefined method `selected_colors' for #

But I don't understand why this is happening, can someone shed some light on this?

Upvotes: 0

Views: 910

Answers (1)

Max Wong
Max Wong

Reputation: 326

Try to modify action "new", add some lines after @contact definition:

def new
  @contact = {
    :contact_info => Contact.new, #first_name, last_name, email, etc.
    :selected_colors => Array.new
  }
  # changes here
  @contact.instance_eval do
    def selected_colors
      self[:selected_colors]
    end
  end
end

What this line does is just add a singleton method for hash @contract. Hope this works.

Upvotes: 1

Related Questions