我有一个 Rails 项目,我必须在不刷新页面的情况下将订阅者数据保存在数据库中!
所以我编写了一个 Ajax 按钮。当我单击按钮时,会弹出一个警报并返回刚刚创建的新用户的 ID。问题是当我查看 Rails 控制台以获取模型User.last的最后一条记录时,该记录的所有字段均为零(ID 除外)。我该如何解决这个问题?
路线:
users_new GET /users/new(.:format) users#new
users GET /users/index(.:format) users#index
create POST /users/create(.:format) users#create
这是我在 app/views/users/new.html.haml 中的看法
.form1
%h1
Subscriber
=form_for @user do |form|
- unless @user.errors.empty?
- @user.errors.full_messages.each do |message|
.alert.alert-danger
%ul
- @user.errors.full_messages.each do |message|
%li= message
%div{ :data => { :role => :content} }
.row.form-group
.col-lg-3
%label
Email:
=form.text_field :email, :class => 'form-control'
.row.form-group
.col-lg-3
%label
Name:
=form.text_field :name, :class => 'form-control'
.row.form-group
.col-lg-3
%label
Phone Number:
=form.text_field :phone_number, :class => 'form-control'
.row.form-group
.col-lg-3
%label
Address:
=form.text_field :address, :class => 'form-control'
%ui-grid-a
%ui-block-a
%a.primary{ :data => { :role => :button, :remote => create_path, :parent => '.form1', :success => 'saved' } } Save
这是控制器:
class UsersController < ApplicationController
def index
end
def new
@user = User.new
end
def create
@user = User.new params[:user]
@user.save
render :json => @user
end
end
我的 js 文件:
function saved(user){
alert(user.id);
}