我有一个 Rails 3 应用程序,它试图一次发布一组用户。我正在尝试通过 Postman REST 客户端发帖。如果我尝试一次发布一个用户,效果很好,但一次发布多个用户是不可能的。
这是我的用户模型:
class User < ActiveRecord::Base
attr_accessible :name,age,email,mobile,gender
end
我的用户控制器:
respond_to :html , :json
def create
@user = User.new(params[:user])
if @user.save
render :json => { :status => :ok, :message => "User Created Successfully"}.to_json
end
end
用户以 JSON 格式为多个用户发布数据:
{
user:[
{
"name":"abc",
"age": 23,
"email": "abc@gmail.com",
"mobile": 9876543210,
"gender":"M"
},
{
"name":"def",
"age": 26,
"email": "def@gmail.com",
"mobile": 9876543210,
"gender":"F"
}
]
}
在 Rails 中可以做到这一点吗?
我试过了:
def create
@userlist = User.new(params[:user])
@userlist.each do |u|
u.save
end
render :json => { :status => :ok, :message => "User Created Successfully"}.to_json
end
但数据没有保存。
有什么解决办法吗?
在用户下保存的嵌套属性:
{
"users" :[
{
"name":"abc",
"age": 23,
"email": "abc@gmail.com",
"mobile": 9876543210,
"gender":"M",
"projects":
[
{
"projectname":"abc",
"type":"abc"
},
{
"projectname":"def",
"type":"abc"
},
{
"projectname":"ghi",
"type":"abc"
}
]
},
{
"name":"def",
"age": 26,
"email": "def@gmail.com",
"mobile": 9876543210,
"gender":"F",
"projects":
[
{
"projectname":"abc",
"type":"abc"
},
{
"projectname":"def",
"type":"abc"
},
{
"projectname":"ghi",
"type":"abc"
}
]
}
]
}