Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

NoMethodError in Customer#index

undefined method `to_key'

<%= form_for Customer do |f| %>

      <div class="field">
          <%= f.label :title %><br>

class CustomerController < ApplicationController
    def index
        @customers = Customer.all
    end

    def new
        @customer = Customer.new
    end


end

<%= form_for Customer do |f| %>

    <div class="field">
        <%= f.label :title %><br>
        <%= f.text_field :title %>
    </div>
    <div class="field">
        <%= f.label :fullname %><br>
        <%= f.text_field :fullname %>
    </div>
    <div class="field">
        <%= f.label :first_name %><br>
        <%= f.text_field :first_name %>
    </div>
    <div class="field">
        <%= f.label :middle_name %><br>
        <%= f.text_field :middle_name %>
    </div>
    <div class="field">
        <%= f.label :last_name %><br>
        <%= f.text_field :last_name %>
    </div>
<% end %>

1 Answer

Hi Austin!

I'm a fan of moving model logic to a controller and accessing it through that. Your issue is that you're calling form_for on a Class but not instantiating an instance of that class. Sounds like a bunch of hodge podge right?

Try this:

In app/controller/customers_controller.rb

class CustomerController < ApplicationController
  def index
    @customers = Customer.all
    @new_customer = Customer.net
  end

  def new
    @customer = Customer.new
  end
end

Then in app/views/customers/index.html.erb:

Change this line

<%= form_for Customer do |f| %>

to this

<%= form_for @new_customer do |f| %>

What we're doing here is instantiating a new customer object, then assigning the attributes via the form. We could reproduce this same logic in our console, like so

@new_customer = Customer.new
@new_customer.first_name = 'Austin'
@new_customer.last_name = 'Klenk'

But, instead of using the console (obviously people cannot use your site through your console!) we map the object to a web form. The user uses our form fields to enter the data, and we assign the object's attributes on the back end. The fun of programming!

Hope this helps.