Ad

Nomethoderror In Contacts#new Making Contactform In Ruby

- 1 answer

I am new to ruby on rails and i am currently stuck trying to create a contact form. I get the report saying : undefined method `name' for #, but in the i did create the method for name : create_table :contacts do |t| t.string :name I'v tried to fix this error so i can preview the page, but i keep getting an error. I hope one of you can help me, thanks in advance!

NoMethodError in Contacts#new
Showing /home/nitrous/workspace/simplecodecast_saas/app/views/contacts/new.html.erb where line #7 raised:

undefined method `name' for #<Contact id: nil>
Extracted source (around line #7):

          
    <%= form_for @contact do |f| %>                  
      <div class="form-group">
        <%= f.label :name %>
        <%= f.text_field :name, class: 'form-control' %>       <---- (This is line 7)
      </div>
  
      <div class="form-group">

Rails.root: /home/nitrous/workspace/simplecodecast_saas

Application Trace | Framework Trace | Full Trace
app/views/contacts/new.html.erb:7:in `block in _app_views_contacts_new_html_erb__2291340040590759835_34535240'
app/views/contacts/new.html.erb:4:in `_app_views_contacts_new_html_erb__2291340040590759835_34535240'
Request

Parameters:

None
Toggle session dump
Toggle env dump
Response

Headers:

None

My routes.rb code:

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

I added this to my model: contact.rb

class Contact < ActiveRecord::Base
  
end

And the db file:

class CreateContacts < ActiveRecord::Migration
  def change
  create_table :contacts do |t|
      t.string :name
      t.string :email
      t.text :comments
      
      t.timestamps
    end
  end
end

and last my html page

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

Ad

Answer

I found a fix. I ran the rake db:rollback cmd and then the rake db:migrate.
Now it is working.

Sorry for wasting your time :) Hopefully someone else can benifit from this answer!

Ad
source: stackoverflow.com
Ad