I am trying to post a Javascript object to my Rails API in order to create a model object on my server.
Here is how I define my Javascript object (coffee script) :
createList: (list) ->
params =
list:list
$$.post 'http://localhost:3000/lists.json', params, ((response) ->
), 'json'
So the function parameter contains the list I want to save.
In Rails, I simply create the list :
@list = List.create name:params[:list]
if @list.save
head :ok
else
respond_with error:'Error while creating the list.'
end
I get the following error : undefined method `stringify_keys' for "[object Object]":String
This is how the params
variable is set in Rails :
Parameters: {"list"=>"[object Object]"}
I tried using the JSON.stringify
method in JS, but then my params hash became unreadable :
JSON.stringify(params)
Gives
# Parameters: {"0"=>"{", "1"=>"\"", "2"=>"l", "3"=>"i", "4"=>"s", "5"=>"t", "6"=>"\"", "7"=>":", "8"=>"{", "9"=>"\"", "10"=>"n", "11"=>"a", "12"=>"m", "13"=>"e", "14"=>"\"", "15"=>":", "16"=>"\"", "17"=>"m", "18"=>"a", "19"=>"m", "20"=>"a", "21"=>"\"", "22"=>",", "23"=>"\"", "24"=>"p", "25"=>"r", "26"=>"o", "27"=>"g", "28"=>"r", "29"=>"e", "30"=>"s", "31"=>"s", "32"=>"\"", "33"=>":", "34"=>"\"", "35"=>"0", "36"=>"/", "37"=>"0", "38"=>"\"", "39"=>",", "40"=>"\"", "41"=>"p", "42"=>"r", "43"=>"o", "44"=>"g", "45"=>"r", "46"=>"e", "47"=>"s", "48"=>"s", "49"=>"_", "50"=>"b", "51"=>"a", "52"=>"r", "53"=>"\"", "54"=>":", "55"=>"0", "56"=>",", "57"=>"\"", "58"=>"t", "59"=>"h", "60"=>"u", "61"=>"m", "62"=>"b", "63"=>"\"", "64"=>":", "65"=>"\"", "66"=>"d", "67"=>"e", "68"=>"f", "69"=>"a", "70"=>"u", "71"=>"l", "72"=>"t", "73"=>".", "74"=>"j", "75"=>"p", "76"=>"g", "77"=>"\"", "78"=>"}", "79"=>"}"}
UPDATE
I don't understand why, but now, if I pass the list as-is (without trying to nest it inside a params hash), and in Rails, I set all the attributes manually (@list.name = params[:name]
and so), my problem is solved.
I would prefer to simply write @list.update_attributes(params[:list])
though.
JavaScript
question.$$.post
is from QuoJS and acts like jQuery's$.post
.$.param()
api.jquery.com/jQuery.param on yourparams
coffeescript object. What exactly doeslist:list
look like?