Alfons Ingomar Alfons Ingomar - 6 months ago 12
Ruby Question

Updating objects in RoR with API call

I am trying to configure my ruby on rails application in such a manner that I can update values with http Patch calls from for example a Angular app. Currently I have the following method of which I expect it to work:

users_controller.rb

def safe_params
params.require(:id).permit(:email)
end

def update
user = User.find(params[:id])
user.update_attributes(safe_params)
render nothing: true, status: 204
end


However, I get the following error when I pass some simple JSON:


undefined method `permit' for "500":String


Passed JSON:

{"email":"newadres@live.com", "id":500}


Do you guys know what I am doing wrong?

Answer

I believe you are misunderstanding the purpose of require and permit.

require is generally used in combination with a Hash and a form, to make sure the controller receives an Hash that exists and contains some expected attributes. Note that require will either raise, or extract the value associated with the required key, and return that value.

permit works as a filter, it explicitly allows only certain fields. The returned value is the original params Hash, whitelisted.

In your case, require does not make any sense at all, unless you pass a nested JSON like this one

{"user": {"email":"newadres@live.com", "id":500}}

but even in that case, it would be

params.require(:user).permit(:email)

In your current scenario, the correct code is

params.permit(:email)
Comments