Reputation: 13388
Using Rails 4 and native Javascript (vanilla).
I have the following Ajax call, which returns the place
object:
// place.js
function addPlace(place) {
console.log(JSON.stringify(place));
var xhr = new XMLHttpRequest();
xhr.open("POST", "<%= Rails.application.routes.url_helpers.places_path %>", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.setRequestHeader("X-CSRF-Token", CSRF.token());
xhr.send("place=" + JSON.stringify(place));
}
In the console.log(JSON.stringify(place))
, I get the following JSON:
{"name":"San Francisco","url":"https://maps.google.com/?q=San+Francisco,+CA,+USA&ftid=0x80859a6d00690021:0x4a501367f076adff","utc_offset":-480,"vicinity":"San Francisco","html_attributions":[]}
This params is sent to a Rails controller:
# places_controller.rb
class PlacesController < ApplicationController
def create
abort params[:place].inspect
@place = Place.find_or_create_by(source_id: params[:source_id])
@place.save
head :ok
end
end
In the line abort params[:place].inspect
, instead of showing the whole load, it only shows:
"{"name":"San Francisco","url":"https://maps.google.com/?q=San+Francisco,+CA,+USA"
The url
gets stripped off because of the &
in &ftid=0x80859a6d00690021:0x4a501367f076adff
.
Questions
How should I properly pass a Javascript object (preferably Hash) to Rails controller so that I can properly save it in the DB?
Upvotes: 0
Views: 910