Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update_attribute vs update_attributes Rails 4

I am trying to update attributes of an object after a certain action. If I use update_attribute everything saves correctly to the db but I have many things I need updated so it gets very repetitive.

This works fine:

order.update_attribute(:order_completed, "true")
order.update_attribute(:stripe_email, params[:stripeEmail])

However when I try to use update_attributes my data does not save to the db.

Here is that code:

order.update_attributes(order_completed: "true", stripe_email: params[:stripeEmail])

Does anyone see where my mistake is? From everything I've read that should have worked. Thanks for your help!

like image 998
Kelly Avatar asked Apr 08 '15 19:04

Kelly


1 Answers

update_attributes will fire validations, whereas update_attribute will not. If you know you want to bypass validations the best approach for saving attributes from a Hash is to do this:

order.attributes = { order_completed: "true", stripe_email: params[:stripeEmail] }
order.save(validate: false)

To see what's failing take a look in order.errors or change your call to update_attributes! (with the !) which will raise an exception showing what validation failed.

Rails 4 Update

update_attributes and update_attributes! are aliases for update and update! in Rails 4+.

like image 182
pdobb Avatar answered Sep 25 '22 23:09

pdobb