我正在设置联系表格。但它不起作用。我收到了一条错误消息,如
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: "from@example.com"
def sent(contact)
@contact = contact
mail(:to => "xxxxxxxxx@gmail.com", :subject => 'TsundokuBuster発お問い合わせ')
end
end
答案 0 :(得分:1)
问题出在路线上:
get "static_pages/contact"
post "static_pages/contact"
当您访问联系人页面时,您正在调用一个帖子请求,该请求通常会为名称和其他属性发送空值。
我会删除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
将add resources :contacts, :except => [:show]
添加到routes.rb