1
\$\begingroup\$

I have the following rails grape api endpoint in the users resource:

    desc 'updates a user'
    params do
      optional :first_name, type: String
      optional :active, type: Boolean
      optional :second_name, type: String
      optional :rating, type: Integer
      requires :id, type: Integer
    end
    put ':id' do
      user = User.find_or_create_by(id: params[:id])
      user.name = params[:name] if params[:name].present?
      user.active = params[:active] if params[:active].present?
      user.second_name = params[:second_name] if params[:second_name].present?
      user.rating = params[:rating] if params[:actratingve].present?
      user.save!
    end

Any nicer way to update model without asking per line if the param is present?

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$
user.assign_attributes(params)
user.save

model.assign_attributes(hash) allows you to assign a key value hash to your ActiveRecord object. The only caveat is that the keys passed must correspond to your columns or an exception will be raised. You will need to call .save to persist the changes.

If you want to assign and save in one fell stroke, use model.update(hash).

http://api.rubyonrails.org/classes/ActiveRecord/AttributeAssignment.html

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I did upvote your answer, but you could add a bit of text to add a bit of meat to your answer. This is not Stakc Overlfow, we really to help OP and others readers to improve. You probably should mention what assign_attributes so reader can have it directly in your answer do not needs to read the doc. \$\endgroup\$
    – Marc-Andre
    Jun 28, 2016 at 15:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.