I know that in Rails you can call model.update_attribute :foo, 'bar' and it will update just that one attribute in the db without validating the rest of the model. This causes one SQL transaction.
You can also set multiple attributes with .update_attributes, but this cannot skip validations.
Or, you can call .save( :validate=>false ) and update the model without validation. However, this saves all the attributes on the model in their current state, rather than being able to limit this to certain columns.
My question is, is there any way to set more than one value on a model, but not all of them, without triggering validations, in a single SQL transaction?
Why don't you just set attributes and then call save with :validate => false?
@record.attributes = your_hash # won't nil non-mentioned attributes, as you expect it to
@record.save :validate => false
There are a number of ways to consider going depending on what you want. You can set your attributes and then call save with validate: false
model.attribute = value
model.other_attribute = other_value
model.save(validate: false)
You can also use update_columns. It is the fastest way to write to your db, but keep in mind that this will not only skip validations, it also skips callbacks, and it will even skip updating updated_at.
model.update_columns(attribute: value, other_attribute: other_value)
https://apidock.com/rails/ActiveRecord/Persistence/update_columns
Based on some of your comments it sounds like assign_attributes might actually be what you want. This won't save to the database at all, but sets the attributes so that you can save after your form is complete. Again, there are a number of ways to go depending on your specific need.
https://api.rubyonrails.org/v6.0/classes/ActiveModel/AttributeAssignment.html#method-i-assign_attributes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With