Search code examples
ruby-on-railsserializationnested-attributesrails-api

How to render errors as nested hash instead on single-level hash when using accepts_nested_attributes_for?


In my Rails application I have two models with has_many/belongs_to relations - Farmer and Animal.

class Farmer
  has_many :animals
  accepts_nested_attributes_for :animals
end

class Animal
  belongs_to :farmer
  validates_numericality_of :age, less_than: 100
end

I want to implement create method for Farmer that will also create nested animals.

class FarmerController < ApplicationController
  def create
    @farmer = Farmer.new(farmer_params)
    if @farmer.save
      render json: @farmer
    else
      render json: { errors: @farmer.errors }, status: :unprocessable_entity
    end
  end

  private

  def farmer_params
    params.require(:farmer).permit(
      :name,
      { animals_params: [:nickname, :age] }
    )
  end
end

Animal validates age field and if validation fails, method returns errors hash. So when I'm trying to create farmer with the following json

{
  "farmer": {
    "name": "Bob"
    "animals_attributes: [
      {
        nickname: "Rex",
        age: 300
      }  
    ]
  }
}

I get this error:

{
    "errors": {
        "animals.age": [
            "must be less than 100"
        ]
    }
}

But I want to get errors as nested hash (cause of frontend requirements), just like this:

{
    "errors": {
        "animals":[
            {
                age: [
                    "must be less than 100"
                ]   
            }
        ]
    }
}

How can I achieve this?


Solution

  • Didn't found standard way to do it, so I settled it with my own parser.