简体   繁体   English

将JSON对象传递为模型作为有效负载

[英]Passing json object to model as payload

Im having an issue on my rails app. 我在rails应用程序上遇到问题。 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 : 使用XMLHttpRequest我将json对象发送到我的数据库:

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 : 我的迁移设置为接受json对象作为有效负载:

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 : 我的Tournois控制器是我认为遇到一些困难的地方:

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. 这是每次我尝试提交括号时出现的问题,我的终端上出现了我的json对象stringify的内容,POST参数似乎通过了,我的有效载荷参数成为了我的json对象的内容,但是由于某种原因我得到了参数错误(分配属性时,必须将哈希作为参数传递。)这会使我的迁移回滚。

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: 由于您的Rails端点需要表单数据,因此请像这样发送JSON:

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: 然后,假设您正在使用支持JSON类型字段的Postgres,则需要将“有效载荷”参数解析为哈希值,并需要指定字段名称:

Tournoi.new(payload: JSON.parse(params[:payload]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM