I have a Rails application that is trying to update multiple users at a time in User table.
I tried giving multiple ids separated with ‘,’ ,but fails and getting error like “no route matches”, i have created a custom method “assign” , with route specified as ,
"assign/:id" => "users#assign" , :via => [:put]
I am trying to update through POSTMAN REST Client.
My PUT Request,
http://localhost:3000/assign/6,7,8 --- PUT
data:
{
"users":[
{
"trainerid":4
},
{
"trainerid":5
},
{
"trainerid":6
}
]
}
Mu Controller
def assign
@ids = params[:id].split(",")
@users = params[:users]
@ids.each_with_index do |i|
@user = User.find(i)
@user.updateattributes(@users[index])
end
render :json => { :status => :ok, :message => "User Updated Successfully"}.to_json
end
Here i am trying to update trainerid in users table with id: 4 ,5 ,6
Is it possible to update in another way.
Any help is appreciated…..
Why put the IDs in the URL? Splitting the string feels wrong. Why not just have a simpler route, just to users/assign? Then in your JSON you can have:
And deal with it thus:
Obviously it needs error handling etc, but that’s the basic method. Note that update_attributes will only update those attributes flagged as attr_accessible, so you don’t have to worry about the IDs’ presence in the hashes.