使用 JSON Rails 创建多个对象

Create multiple objects with JSON Rails

我在使用 json 创建 more than object 时遇到问题。 问题是我应该如何 更改控制器中的创建操作 允许的参数 以使此操作成为可能。不幸的是我没有在网上找到任何解决方案...希望能在这里找到更有经验的人。

我已阅读推荐文章: how to permit an array with strong parameters 但它对我不起作用。

我遇到的错误是:

NoMethodError: #Array:0x007ff6e0030438

的未定义方法“允许”

我改了参数,还是一样的错误!!!

我想从外部服务创建帖子。 目前我用邮递员发送这个json:

{   "post":
    [
        {
            "post_title":"Title 2",
            "post_body":"body of the post 2",
            "user_id": 1
        },
        {
            "post_title":"Title",
            "post_body":"body of the post",
            "user_id": 1
        }
    ]
}

我的控制器:

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :update, :destroy]

  def create
    @post = Post.new(post_params)

    if @post.save
      render json: @post, status: :created, location: @post
    else
      render json: @post.errors, status: :unprocessable_entity
    end
  end

  private

    def set_post
      @post = Post.find(params[:id])
    end

    def post_params
      params.require(:post).permit(:post_title, :post_body, user_ids:[])
    end
end

您的错误是调用 params.require(:post) 造成的。由于您的 posts 是一个数组,而不是常规参数散列,因此 Rails 不允许对其调用 permit。你应该去

def post_params
  params.permit(post: [:post_title, :post_body, :user_id])
end

我终于找到了解决问题的方法。从数组创建对象时,控制器中必须有另一个方法遍历传递的数组

JSON:

{   "posts_list":
    [
       {
           "post_title":"Title 2",
           "post_body":"body of the post 2",
           "user_id": 1
       },
       {
           "post_title":"Title",
           "post_body":"body of the post",
           "user_id": 1
       }
   ]

控制器:

def mass_create
   statuses = []
   params[:posts_list].each do |post_params|
      auth = Post.new(select_permited(post_params))
      statuses << ( auth.save ? "OK" : post.errors )
end if params[:posts_list]

  render json: statuses
end   


def select_permited(post_params)
  post_params.permit(:post_title, :post_body, :user_id)
end

路线:

resources :posts do
  post 'mass_create', on: :collection
end