2013-12-17 45 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