0

I'm creating a Rails API, and I'm trying to receive an array through a post request. On POSTMAN, my request is:

{
    "user": {
        "email": "testuser2@gmail.com",
        "first_name": "Joao Paulo",
        "last_name": "Furtado Silva",
        "city_id": 384,
        "province_id": 2,
        "cuisines": [17,5,2],
        "password":"123456",
        "password_confirmation":"123456"
    }
}

On the user model:

validates :first_name, :last_name, :city_id, :province_id, :cuisines, :password, :password_confirmation, :presence => true

And on User_controller:

def user_params
  params.require(:user).permit(:email, :first_name, :last_name, :city_id, :province_id, :password, :password_confirmation, :cuisines)
end

Even if I pass my cuisines array to the backend, Rails doesn't recognize it. It says as API response:

{
  "status": "Error",
  "message": [
    "Cuisines can't be blank"
  ]
}

What I'm doing wrong here?

If I remove :cuisines from validation, it works fine. But I'm not supposed to do this. What's the best way to solve this issue?

SOLUTION SO FAR:

I removed :cuisines automatic validation from Rails, and validated it manually in a simple code like:

#validate cuisines
@cuisines = params.require(:user)[:cuisines] #it comes in array format

if @cuisines.empty?
  render json: {
    status: 'Error',
    message: 'User cuisines are empty',
  }, status: :precondition_failed

  return false
end

If someone has a better solution, please post.

sawa
  • 165,429
  • 45
  • 277
  • 381
Dr. Joao Paulo
  • 331
  • 1
  • 3
  • 11

2 Answers2

2

To declare that the value in params must be an array of permitted scalar values map the key to an empty array:

def user_params
  params.require(:user).permit(:email, :first_name, :last_name, 
  :city_id, :province_id, :password, :password_confirmation, :cuisines => [])
end

You can see the answer with more details here how to permit an array with strong parameters

Andres23Ramirez
  • 647
  • 1
  • 4
  • 14
1

If you are using POSTMAN then try to send it with form-data Please check below image

enter image description here

and in your permit method please add cuisines as array

 params.require(:user).permit(:email, :first_name, :last_name, 
  :city_id, :province_id, :password, :password_confirmation, :cuisines => [])
Vishal
  • 7,113
  • 6
  • 31
  • 61