$ .AJAX用于在rails中创建多个记录
我正在使用Ruby on Rails,我有一个可以通过AJAX创建post的按钮,使用这个:
$.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", } } });
例如,如何格式化数据以一次创建多个post
posts = [ { title: "Cheese", content: "Cake" }, { title: "Key Lime", content: "Pie" } ]
所以我可以用一个POST插入多个对象?
我有一个标题和内容列表。 我可能需要构建一个JSON对象吗?
无论这是否是好Rails练习,我该怎么做? 另外,我在哪里可以查找如何格式化此类HTTP请求?
你的jQuery调用不会有太大变化:
$.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[:posts]
以一系列哈希的forms访问您的post。
class ThingsController < ApplicationController def batch_create params[:posts].each do |post| Post.create post end end end
说明
使用JSON.stringify
您的数据序列化为JSON。 将contentType
设置为application/json
,将“Content-Type:'application / json'”标头添加到POST。 这将提示Rails将您的POST解释为JSON。