I want to make a patch request with Restangular to update user atrributes. So, a write this:
user.patch(user: user).then(function (result) ...
I'm using grape framework in rails and my controller looks like this:
desc 'Update a user'
params do
requires :user, type: Hash, desc: "user attributes" do
optional :email, type: String, allow_blank: false, regexp: /.+@.+/, documentation: { example: '[email protected]' }
optional :password, type: String, allow_blank: false
optional :firstname, type: String
optional :lastname, type: String
optional :city, type: String
optional :date_of_birth, type: Date
end
end
patch ':id' do
puts params.to_h
user = User.find(params[:id])
user.update(params[:user].to_h)
user
end
Unfortunately, i don't have atrribute routes i my user model, so rails shows this error:
ActiveRecord::UnknownAttributeError (unknown attribute: route):
app/controllers/api/v1/users.rb:44:in `block (2 levels) in <class:Users>'
What should i do? Delete this atrribute in angular or in rails? It is possible to update model with only params that i choose?
Keep in mind that it's best to create/update records ONLY with parameters you want to be permitted - and you can easily do this with Grape.
Grape has a handy declared
method that accepts params
with optional include_missing argument. So you can write a helper that filters out any parameters not declared in params do ... end
block:
def permitted_params
@permitted_params ||= declared(params, include_missing: false).to_h
end
And then in your controller:
patch ':id' do
user = User.find(params[:id])
user.update(permitted_params[:user])
end