Search code examples
ruby-on-railsjsonrubyruby-on-rails-5strong-parameters

Create multiple objects with JSON Rails


I have problem with creating more than object with json. Question is how should I change create action in controller and permited parameteres to make this action possible. Unfortunatelly I didn't find any solutions in net... Hope to find someone more experienced here.

I have read suggested article: how to permit an array with strong parameters but it doesn't work for me.

Error I have is:

NoMethodError: undefined method `permit' for #Array:0x007ff6e0030438

I have changed parameters, but still have the same error!!!!

I want to create posts from external service. At the moment I send this json with Postman:

{   "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
        }
    ]
}

My controller:

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

Solution

  • I finally found a solution to my problem. When creating an object from an array, there have to be another method in controller that iterates through passed array

    The 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
           }
       ]
    

    Controller:

    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
    

    Routes:

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