matQ
matQ

Reputation: 617

Rails 5 Api create new object from json with nested resource

this is the json received as parameters from external angular webapp:

{
  "provincia": {
    "id": 1,
    "name": "Province"
  },
  "username": "tester",
  "direccion": "new avenue 100",
  "email": "[email protected]"
}

this is my controller

 def create
   @seller = Seller.new(seller_params)

  if @seller.save
    render json: @seller, status: :created, location: @seller
  else
    puts @seller.errors.full_messages
    render json: @seller.errors, status: :unprocessable_entity
  end
end

this is seller_params

def seller_params
    params.require(:seller).permit(:username, :direccion, :email, :provincia_id)
end

models: Seller belongs_to Provincia

server console output error full message

Provincia must exist

Which modification in the Rails API should I do to make it work, and save the new seller? thanks in advance.

Upvotes: 1

Views: 641

Answers (2)

Leonardo da Rosa
Leonardo da Rosa

Reputation: 31

The way that you are permiting your params in the controller are not correct:

Rails Docs

You need to pass your provincia_id in your attributes or permit the attributes that you are passing to your controller

Way 1:

{
  "provincia_attributes": {
    "id": 1,
    "name": "Province"
  },
  "username": "tester",
  "direccion": "new avenue 100",
  "email": "[email protected]"
}

SellersController.rb

def seller_params
  params.require(:seller).permit(:username, :direccion, :email, provincia_attributes: [:id, :name])
end

Way 2

{
  "provincia_id": "1"
  "username": "tester",
  "direccion": "new avenue 100",
  "email": "[email protected]"
}

SellersController.rb

def seller_params
  params.require(:seller).permit(:username, :direccion, :email, :provincia_id)
end

Upvotes: 3

arieljuod
arieljuod

Reputation: 15838

Try changing the params like this:

def seller_params
  p = params.require(:seller).premit(:username, :direccion, :email).to_h
  p[:seller][:provincia_id] = params[:seller][:provincia][:id]
  p
end

That will add the "provincia_id" key you are missing for the association. I call to_h to get a new hash because I don't like to mutate the original params and you have already permited the values you want so that Hash is safe to use.

Upvotes: -1

Related Questions