我在rails代码上写ruby。我正在使用ajax请求从客户端向服务器发送数据。但问题是它不会将数据保存到数据库中。因为我对铁轨上的红宝石完全不熟悉,所以我不知道为什么它不起作用。我也没有任何错误
这是我的代码
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'}
答案 0 :(得分:2)
看起来您的HTML输入名称和控制器无法协同工作。通常在Rails中,当您使用the built-in form helpers时,所有字段名称都用您的模型命名:
<input name="contact[name]">
这使您可以在控制器中执行Contact.new(params[:contact])
之类的操作。在你的情况下,我不知道表单发生了什么,因为你没有发布它,但我假设你是如何访问控制器中的params变量的,这就是问题所在。我建议使用表单助手,以便您的HTML遵循命名空间参数的预期约定。然后,您将能够将控制器更改为:
@contacts = Contact.new(params[:contact])
if @contacts.save
redirect_to root_path, :notice => "your post is saved"
else
render "new"
end
需要注意的一点是,使用params盲目地实例化对象会导致安全漏洞。请务必阅读security guide section on mass-assignment以便更好地理解这一点。