我正在编写 ruby on rails 代码。我正在使用 ajax 请求将数据从客户端发送到服务器。但问题是它不会将该数据保存到数据库中。由于我对 ruby on rails 完全陌生,所以我不知道为什么它不起作用。我也没有收到任何错误
这是我的代码
class ContactsController < ApplicationController
def contacts
name = params["name"]
company = params["company"]
email = params["email"]
phone = params["phone"]
@contacts = Contact.new(params[:post])
if @contacts.save
redirect_to root_path, :notice => "your post is saved"
else
render "new"
end
end
end
这是我的js代码
$('.signupbutton').click(function(e) {
e.preventDefault();
var data = $('#updatesBig').serialize();
var url = 'contacts';
console.log(data);
$.ajax({
type: 'POST',
url: url,
data: data,
success: function(data) {
console.log('done');
}
});
});
这是我在控制台中的输出
Started POST "/contacts" for 127.0.0.1 at 2012-07-13 13:25:41 +0300
Processing by ContactsController#contacts as */*
Parameters: {"name"=>"asdsa", "company"=>"asdsa", "email"=>"asdasd", "phone"=>"asdasd"}
(0.1ms) begin transaction
SQL (18.1ms) INSERT INTO "contacts" ("company", "created_at", "email", "group", "name", "phone", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["company", nil], ["created_at", Fri, 13 Jul 2012 10:25:41 UTC +00:00], ["email", nil], ["group", nil], ["name", nil], ["phone", nil], ["updated_at", Fri, 13 Jul 2012 10:25:41 UTC +00:00]]
(3.9ms) commit transaction
Redirected to http://0.0.0.0:3000/
Completed 302 Found in 33ms (ActiveRecord: 22.5ms)
更新
这是我的html表单。我正在使用 haml 而不是计划 html.erb
%form#updatesBig{:target => 'contacts', :method => 'post'}
%div
%label{:for => 'form_updatesBig_name'} Name
%input{:type => "text", :id => 'form_updatesBig_name', :name => 'name', :class => 'text name required'}
%label{:for => 'form_updatesBig_company'} Organization
%input{:type => "text", :id => 'form_updatesBig_company', :name => 'company', :class => 'text company required'}
%div
%label{:for => 'form_updatesBig_email'} E-mail
%input{:type => "text", :id => 'form_updatesBig_email', :name => 'email', :class => 'text email required'}
%label{:for => 'form_updatesBig_phone'} Phone
%input{:type => "text", :id => 'form_updatesBig_phone', :name => 'phone', :class => 'text phone required'}
%div
%input.button.signupbutton{:type => 'submit', :value => 'Sign up'}