mrkmn
mrkmn

Reputation: 13

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

Upvotes: 0

Views: 400

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

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.

Upvotes: 0

matanco
matanco

Reputation: 2129

According to your Image with the error there is no name field in contacts please rerun the migration or add those fields.

#< contacts id: nil>

means contacts has only id so what i guess you did is adding those fields after run this migration which will not invoke the database!

please recreate migration for those fields and remove them from the original file and all should be fine.

don't ever add things to migration file after you run it this can cause big problems when deploy this app from scratch.

Upvotes: 1

Related Questions