使用 JSON Rails 创建多个对象

埃尔穆齐克

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

我已阅读建议文章:如何允许具有强参数的数组,但它对我不起作用。

我的错误是:

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
埃尔穆齐克

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章