简体   繁体   中英

TypeError (no implicit conversion of nil into String) ruby on rails 5

So I have a controller that accepts a JSON as payload

def create
     @tournoi = Tournoi.new(payload: JSON.parse(params[:payload]))
    if @tournoi.save
      redirect_to root_url
        flash[:success] = "Your tournament bracket has been validated!"

the json is from a js diagram that's editable, I am saving the JSON with XMLHttpRquest and formData :

 function save() {
      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);
                    }

The JSON is successfully inserted into my controller, I get redirected to a TypeError landing page on my create method from my tournois controller, I know my payload is nill before I save it, I don't know why the way I declared @tournoi = Tournoi.new(payload: JSON.parse(params[:payload])) isn't guaranteeing the conversion from nill to payload..

you did a wrong way to submit payload json to rails backend. So params is not json, it's string of json You can try to remove this

var json = JSON.stringify(tojs); 

line from code, and add tojs to formdata directly

formData.append("payload", tojs);

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.

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