Question

I am setting a contact form. But it doesn't work. I got an error message like

SQLite3::ConstraintException: contacts.name may not be NULL: INSERT INTO "contacts" ("content", "created_at", "email", "name", "updated_at") VALUES (?, ?, ?, ?, ?)

.

It seems like this error comes from controller setting because I get this error message before the form shows. I mean I couldn't see any form on static_pages/contact. Could you give me some advice?

☆static_pages_controller

 def contact
  @contact = Contact.new(params[:contact])
  if @contact.save
    ContactMailer.sent(@contact).deliver
    redirect_to :action => :contact, :notice => 'お問い合わせありがとうございました。'
  else
    render :action => :contact, :alert => 'お問い合わせに不備があります。'
  end
end

☆contact.html.erb

<h1>お問い合わせフォーム</h1>

<%= form_for(@contact) do |f| %>
  <% if @contact.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@contact.errors.count, "error") %> prohibited this contact from being saved:</h2>

      <ul>
      <% @contact.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.string_field :name %>
  </div>
  <div class="field">
    <%= f.label :email %><br />
    <%= f.string_field :email %>
  </div>
  <div class="field">
    <%= f.label :content %><br />
    <%= f.text_field :content %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

☆routes.rb

 get "static_pages/contact"
  post"static_pages/contact"

☆contact.rb

class Contact < ActiveRecord::Base
  attr_accessible :name, :email, :content
end

☆contact_mailer.rb

class ContactMailer < ActionMailer::Base
  default from: "from@example.com"

  def sent(contact)
    @contact = contact

    mail(:to => "xxxxxxxxx@gmail.com", :subject => 'TsundokuBuster発お問い合わせ')
  end
end
Was it helpful?

Solution

the problem is in routes:

get "static_pages/contact"
post "static_pages/contact"

when you are accessing contact page you are calling a post request that normally sends empty values for name ant other attributes.

I'd remove the post "static_pages/contact" line and leave the form to use create action when hitting the submit.

 def contact
  @contact = Contact.new
 end

contacts_controller.rb

def create
  @contact = Contact.new(params[:contact])
  if @contact.save
    ContactMailer.sent(@contact).deliver
    redirect_to :action => @contact, :notice => 'お問い合わせありがとうございました。'
  else
    render :action => 'new' :alert => 'お問い合わせに不備があります。'
  end
end

add add resources :contacts, :except => [:show] to routes.rb

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top