PATCH and PUT Rails

Asked

Viewed 116 times

-1

I am doing a test for an internship where I have an api and in this api I have to have the PUT method to change a user’s data by the id and a PATCH method that changes the partial data of a user but if it does not exist will create it.

def update
    @user = ApiModel.find(params[:id])


    @user.update(user_params)
end

What is the best way to make the PATCH so that if there is no user create it?

1 answer

0

The call ApiModel.find(params[:id]) will fire an exception if the record does not exist in the bank (I am assuming you are using ActiveRecord).

You can use the ApiModel.find_by(id: params[:id]) to make the query without an exception being triggered. So as a result you will have the user found or null (nil) in return.

Then just control the flow with @user.present? and take the necessary action.


I was going to suggest you make the call ApiModel.where(id: params[:id]).first_or_create, but I need to warn you that it is strange for someone to call your API to partially update a user with an ID that doesn’t exist. I say this because if the user does not exist, it will be created with a different ID than it was passed in the API (by relying on a sequential database value).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.