在轨道创造多个记录$阿贾克斯多个、轨道、阿贾克斯

2023-09-10 16:57:03 作者:你喝二氧化碳长大的吧。

我使用on Rails的Ruby和我有一个按钮,可以创建通过AJAX后,利用这样的:

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?

予有标题和内容的列表。我可能会构造一个JSON对象了这些?

I have a list of titles and contents. Might I have to construct a JSON object out of these?

不管这是否是好Rails的做法,我该怎么办呢?另外,我在这里可以寻找如何格式化这样的HTTP请求?

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?

推荐答案

您jQuery的通话不会有太大变化:

Your jQuery call won't change much:

$.ajax({
  beforeSend: function(xhr) {
    xhr.setRequestHeader(
        'X-CSRF-Token', 
        $('meta[name="csrf-token"]').attr('content'))},
  url: "/posts/",
  type: "POST",
  contentType: "application/json",
  data: JSON.stringify({
    posts: [
      {
        title: "Cheese",
        content: "Cake",
      },
      {
        title: "Key Lime",
        content: "Pie"
      }
    ]          
  })
});

在你的Rails动作,你将能够通过 PARAMS访问您的文章作为哈希数组[:帖子]

In your Rails action, you will be able to access your posts as an array of hashes via params[:posts].

class ThingsController < ApplicationController
  def batch_create
    params[:posts].each do |post|
      Post.create post
    end
  end
end

说明

使用 JSON.stringify 将导致数据被序列化为JSON。设置的contentType 应用程序/ JSON 到内容类型:应用/ JSON的添加标题到您的文章。将线索导轨间preT您的文章为JSON。

Using JSON.stringify causes your data to be serialized as JSON. Set contentType to application/json to add the "Content-Type: 'application/json'" header to your POST. That will clue Rails to interpret your POST as JSON.