I’m using Ruby on Rails, and I have a button that can create a post through AJAX, using this:
$.ajax({
beforeSend: function(xhr) {
xhr.setRequestHeader(
'X-CSRF-Token',
$('meta[name="csrf-token"]').attr('content'))},
url: "/posts/",
type: "POST",
data: {
post: {
title: "Cheese",
content: "Cake",
}
}
});
How do I format the data to create multiple posts at once, for example
posts = [
{
title: "Cheese",
content: "Cake"
},
{
title: "Key Lime",
content: "Pie"
}
]
so I can insert multiple objects with one POST?
I have a list of titles and contents. Might I have to construct a JSON object out of these?
Regardless of whether this is good Rails practice, how do I do this? Also, where might I look for how to format such HTTP requests?
Your jQuery call won’t change much:
In your Rails action, you will be able to access your posts as an array of hashes via
params[:posts].Explanation
Using
JSON.stringifycauses your data to be serialized as JSON. SetcontentTypetoapplication/jsonto add the “Content-Type: ‘application/json'” header to your POST. That will clue Rails to interpret your POST as JSON.