1

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.

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Note that provincia_attributes will only create a nested record on the fly if Seller accepts_nested_attributes_for :provincia.
-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.