Hi,
I’m trying to do a simple REST request to my rails app using jQuery
but can’t get the data body right. It looks like parts are working and
parts aren’t. I want to update a model so I have to use PUT, which I
emulate by using a POST request and adding the usual “_method” =>
“put”. This seems to work, but the actual model data does not come
through. Here is the code:
var grpid = 138
var grp_data = {
“_method”: “put”,
“grouping”: {
“pos_x”: col,
“pos_y”: row
}
}
$.post(’/groupings/’+grpid+’.json’, grp_data, null, ‘json’);
All I get in my rails app is:
Processing GroupingsController#update to json (for 127.0.0.1 at
2009-10-28 12:05:33) [PUT]
Parameters: {“grouping”=>"[object Object]", “id”=>“138”}
Grouping Load (0.5ms) SELECT * FROM “groupings” WHERE
(“groupings”.“id” = 138)
NoMethodError (undefined method stringify_keys!' for "[object Object]":String): app/controllers/groupings_controller.rb:68:in
update’
So obviously the “_method” is interpreted correctly (I’ll end up
seeing a PUT) but the data is not. I found a solution for now, which
is the following:
$.ajax({
type: “PUT”,
url:’/groupings/’+grpid+’.json’,
data: JSON.stringify(grp_data),
contentType: ‘application/json; charset=utf-8’
});
But this solution ignores the “_method” information, so if I replace
“PUT” with “POST”, again it doesn’t work (but as far as I understand
“PUT” shouldn’t be used for compatibility reasons).
I’m pretty sure I’m missing something fundamental, since this
operation should be a piece of cake and probably is being used all the
time, so it can’t be that complicated. Especially the JSON.stringify()
in my solution seems clumsy …
Anyone who sees what I’m doing wrong?
BTW: This application is running on rails 2.3.4