2013-12-17 119 views
1

我正在设置联系表。但它不起作用。我收到了一条错误消息,如设置联系表

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

看起来这个错误来自于控制器设置,因为我在表单显示之前得到了这个错误信息。我的意思是我无法在static_pages/contact上看到任何表单。 你能给我一些建议吗?

☆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: "[email protected]" 

    def sent(contact) 
    @contact = contact 

    mail(:to => "[email protected]", :subject => 'TsundokuBuster発お問い合わせ') 
    end 
end 
+1

第一件事,当您试图访问该页面,它会尝试创建联系人记录为您的GET和POST方法映射相同的动作** contact **,并且当时有params [:contact]为零。这是错误的主要原因。结帐,如果有的话。数据库级别的验证。为了显示联系表单,您必须通过其他其他操作(例如新建并在此处呈现您的页面)来调用它。 –

+0

非常感谢!我设置了验证并得到一个新的错误。未定义的方法'联系'为#<联系人:0x007fdf2bbde798> –

+0

使contact.html应该有@contact = Contact.new –

回答

1

问题是出在路线:

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

,当你访问联系人页面要调用POST请求,通常发送空值的名字蚂蚁其他属性。

我想删除post "static_pages/contact"行,并在创建操作时使表单保持在提交状态。

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 

插件添加到resources :contacts, :except => [:show]的routes.rb

+0

非常感谢!我跟着你的指令,但在/ static_pages/contact 未定义的方法'contacts_path'中找到了一个类似于NoMethodError的错误#<#:0x007fdf2f5eaf18>。 –

+0

将路线添加到资源:contacts::except => [:show]' – rmagnum2002

+0

http://chat.stackoverflow.com/rooms/43315/http-stackoverflow-com-questions-20630438-setting-contact-form – rmagnum2002