Im having an issue on my rails app. i'm letting Users submit and filled out bracket once they'r done editing it. :
<%= form_for Tournoi.new do |f| %>
<button id="SaveButton" onclick="save()">Save</button>
<% end %>
Using XMLHttpRequest i send the json object to my db :
function save() {
var data = {};
var tojs = myDiagram.model.toJSON();
data.payload = tojs;
//var parsed_json = JSON.parse(data);
var json = JSON.stringify(data);
myDiagram.isModified = false;
var request = new XMLHttpRequest();
request.onload = callback;
request.open("post", "http://localhost:3000/malesingle", true);
request.setRequestHeader("Content-Type", "application/json");
request.send(json)
my migration is set up in a way that it accepts json object as payload :
class CreateTournois < ActiveRecord::Migration[5.1]
def change
create_table :tournois do |t|
t.json 'payload'
t.timestamps
end
end
end
my tournois controller is where i think im having some difficulties :
def create
@tournoi = Tournoi.new params[:payload]
if @tournoi.save
redirect_to root_url
flash[:success] = "Your tournament bracket has been validated!"
redirect_to @tournoi
else
redirect_to malesingle_url
end
end
Here is the problem every time i try to submit the bracket, the content of my json object stringify appeared on my terminal, the POST argument seem to go through, my payload parameters becomes the content of my json object but for some reason i get a Argument Error (When assigning attributes, you must pass a hash as an argument.) which makes my migration roll back.
I know the error comes from my controller but i cant seem to find where i went wrong or if there is something missing or in the wrong order.
Since your Rails endpoint expects form data, send your JSON like this:
var tojs = myDiagram.model.toJSON();
var json = JSON.stringify(tojs);
var formData = new FormData();
formData.append("payload", json);
var request = new XMLHttpRequest();
request.open("post", "http://localhost:3000/malesingle", true);
request.send(formData);
Then, assuming you're using Postgres which supports fields of type JSON, the "payload" param needs to be parsed into a hash and the field name needs to be specified:
Tournoi.new(payload: JSON.parse(params[:payload]))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.