I'm using Rails 4, and trying to save data via a form, but the process continually fails. I've done my best to look at others who had similar issues but even copying their code doesn't work for me. The end result after filling out my form is receiving the error stating the contact was not saved. Any ideas? Thanks!
controllers/contacts_controller.rb
class ContactsController < ApplicationController
def create
@contact = Contact.new(contact_params)
if @contact.save
flash[:success] = "Contact saved!"
else
flash[:alert] = "Contact not saved!"
end
end
def destroy
end
def new
@contact = Contact.new
end
private
def contact_params
params.require(:contact).permit(:first_name, :last_name, :email)
end
end
views/contacts/new.html.erb
<div class= "panel-body">
<%= form_for(@contact) do |f| %>
<div class="form-group">
<%= f.label :first_name %>
<%= f.text_field :first_name, autofocus: true, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :last_name %>
<%= f.text_field :last_name, autofocus: true, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :email %>
<%= f.email_field :email, autofocus: true, class: "form-control" %>
</div>
<div class="form-group">
<%= f.submit "Add", class: "btn btn-primary" %>
</div>
<% end %>
</div>
config/routes.rb
Rails.application.routes.draw do
resources :contacts, only: [:new, :create, :destroy]
end
models/contact.rb
class Contact < ActiveRecord::Base
validates :first_name, presence: true
validates :last_name, presence: true
validates :email, presence: true
end
db/migrate
class CreateContacts < ActiveRecord::Migration
def change
create_table :contacts do |t|
t.string :first_name
t.string :last_name
t.string :email
t.timestamps
end
end
end