Updating a rails record with vanilla javascript

Viewed 17

Is it possible to update a rails record with vanilla javascript without intercepting the data and converting it to a hash in the controller? Here is my code:

var data = new FormData();
  data.append("authenticity_token", csrf_token_value);
  data.append(
    "user",
    JSON.stringify({
      name: name,
      instagram: instagram,
      employer: employer,
      home_base_id: homeBase,
    })
  );

  fetch(`/${username}/edit`, {
    method: "PUT",
    body: data,
  })
    .then((response) => {
      console.log("response: ", response);
    })
    .catch((error) => {
      console.log("error: ", error);
    });

If I just send the data without stringifying it, it shows up in the rails controller at user: [object, object]. In the update action I update the params like this: params["user"] = JSON.parse(params["user"])

Is there a more straight forward or elegant way to do this?

0 Answers
Related