Rails has multiple methods to update multiple columns at the same time, so I've summarized the differences.
assign_attributes
Features </ strong>
Usage </ strong> (if you have a table called User)
user = User.first
user.assign_attributes(family_name: "foo", given_name: "bar")
user.save
#attribute=in the case of
user.attributes = { family_name: "foo", given_name: "bar" }
It is not saved, so you need to call save.
update_attributes
Features </ strong>
Usage example </ strong>
user = User.first
user.update_attributes(family_name: "foo", given_name: "bar")
#For update
user.update(family_name: "foo", given_name: "bar")
There is no need to call save separately.
update_attributes!
Features </ strong>
Usage example </ strong>
user = User.first
user.update_attributes!(family_name: "foo", given_name: "bar")
#update!in the case of
user.update!(family_name: "foo", given_name: "bar")
The way to return the result is different from update_attributes.
update_columns
Features </ strong>
Usage example </ strong>
user = User.first
user.update_columns(family_name: "foo", given_name: "bar")
Please note that there are no validation checks or callback calls.
reference https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_attributes
Recommended Posts