Search code examples
ruby-on-railsrubyruby-on-rails-3nomethoderror

Ruby On Rails - NoMethodError


Hy guys... i'm learning Ruby on Rail but i don't know whats going on on this page, this is my error:

NoMethodError in Contacts#new Showing /home/ubuntu/workspace/simplecodecasts_saas/app/views/contacts/new.html.erb where line #7 raised: undefined method `name' for #

this is my new.html.erb

<div class="row">
  <div class="col-md-4 col-md-offset-4">
    <div class="well">
      <%= form_for @contact do |f| %>
        <div class="form-group">
          <%= f.label :name %>
          <%= f.text_field :name, class: 'form-control' %>
        </div>
        <div class="form-group">
          <%= f.label :email %>
          <%= f.email_field :email, class: 'form-control' %>
        </div>
        <div class="form-group">
          <%= f.label :comments %>
          <%= f.text_area :comments, class: 'form-control' %>
        </div>
        <%= f.submit 'Submit', class: 'btn btn-default' %>
      <% end %>
    </div>
  </div>
</div>

this is my routes

Rails.application.routes.draw do
  resources :contacts
  get '/about' => 'pages#about'
  root 'pages#home'

and my contacts_controller.rb

class ContactsController < ApplicationController

  def new
    @contact = Contact.new
  end

  def create
  end

end

what is going wrong?

Full Error screen screen


Solution

  • It means your contact record doesn't have any name attribute, the reason being you don't have it in your db.

    To fix it, just run rake db:migrate... or if you haven't created a migration yet, you should follow these steps:

    $ rails g migration AddAttrsToContacts
    
    #db/migrate/add_attrs_to_contacts____.rb
    class AddAttrsToContacts < ActiveRecord::Migration
       def change
           add_column :contacts, :name, :string
           add_column :contacts, :email, :string
           add_column :contacts, :comments, :text
       end
    end
    
    $ rake db:migrate
    

    This will populate the table with the appropriate columns, and should resolve the error.