Reputation: 1290
I am new to rails and trying to understand how this works for several days now. My goal is to post a JSON-file from the browser (different domain) to an Rails application and save the sent data to the database.
Following JQuery-Code is executed:
$(document).ready(function() {
$("#testbutton").click(function() {
var params = '{"comment": "Test", "creator": "Max", "name": "Testname", "url": "www.foo.com"}';
$.ajax({
type: "post",
headers: { 'X-CSRF-Token': '<%= form_authenticity_token.to_s %>' },
accepts: "application/json",
contents: "application/json",
data: params,
url: 'http://localhost:3000/pages'
});
});
});
I skip verifying the autheticity-token in the action-controller:
skip_before_filter :verify_authenticity_token
Now, I don't know what to do in the create-action what I have to change that it will parse the JSON and write it to the database. I use the standard-behavior of the create-action:
def create
@page = Page.new(params[:data])
respond_to do |format|
if @page.save
format.html { redirect_to @page, :notice => 'Page was successfully created.' }
format.json { render :json => @page, :status => :created, :location => @page }
else
format.html { render :action => "new" }
format.json { render :json => @page.errors, :status => :unprocessable_entity }
end
end
end
The server receives the data from the website, but isn't able to parse it.
Started POST "/pages" for 127.0.0.1 at Thu Jun 07 21:48:53 +0200 2012
Processing by PagesController#create as undefined
Parameters: {"{\"data\": {\"comment\": \"Test\", \"creator\": \"Fam Disselhoff\", \"name\": \"Renate\", \"url\": \"www.elesenroth.de\"}}"=>nil}
(0.1ms) begin transaction
SQL (67.5ms) INSERT INTO "pages" ("comment", "created_at", "creator", "name", "updated_at", "url") VALUES (?, ?, ?, ?, ?, ?) [["comment", nil], ["created_at", Thu, 07 Jun 2012 19:48:53 UTC +00:00], ["creator", nil], ["name", nil], ["updated_at", Thu, 07 Jun 2012 19:48:53 UTC +00:00], ["url", nil]]
Upvotes: 0
Views: 2202
Reputation: 2951
You can use the following decode method to process.
parsed_json = ActiveSupport::JSON.decode(params[:data])
new_obj = Whatever.new
new_obj.field1 = parsed_json["field1"]
new_obj.field2 = parsed_json["field2"]
new_obj.save
Hope this helps.
Upvotes: 2