I have a Rails 3 Application that is trying to post an array of users, all at one time. I am trying to post through the Postman REST client. If I tried to post a single user at a time it works well, but it is not possible to post multiple users at a time.
This is my User model:
class User < ActiveRecord::Base
attr_accessible :name,age,email,mobile,gender
end
And my User controller:
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
User posting data in JSON format for multiple users:
{
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"
}
]
}
Is it possible to do this in Rails?
I tried:
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
but the data is not saved.
Is there any solution?
Nested attributes saving under User:
{
"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"
}
]
}
]
}