Pages

Monday, June 1, 2015

Check if ActiveRecord object is valid with params before updating to Database

To update the attributes without saving them, you can use
@obj.assign_attributes( params[:obj] )
Then to check if the object is valid, you can call
@obj.valid?
If the object is not valid, you can see the errors (only after calling .valid?) by calling
@obj.errors
If the object is valid, you can save it by calling
@obj.save
However, all of this usually isn't necessary. If the object isn't valid, then ActiveRecord won't save the object to the database, so all of the attribute changes are forgotten when you leave the controller action.
Also, since an invalid record won't be saved to the database, you can always just call Object.find() again to get the original object back.