📅  最后修改于: 2023-12-03 15:34:36.702000             🧑  作者: Mango
In Ruby on Rails, updating records is a common task. However, sometimes we may want to skip the validation process during an update, for example, when we need to mass-update records, or when we want to update a record with specific attributes without triggering other validations.
Thankfully, Rails provides an easy way to update records without activating validations. In this tutorial, we will explore how to update records without validations in Rails.
update_column
MethodThe easiest way to update a single column without validations is to use the update_column
method.
# Find the record you want to update
post = Post.find(1)
# Update the column without validation
post.update_column(:title, "New Title")
As you can see, the update_column
method accepts two arguments: the name of the column to update, and the new value for that column. This method bypasses all validations, callbacks, and saves the record immediately. It is ideal for updating a single column when validation is not required.
update_columns
MethodThe update_column
method only updates one column at a time. If you need to update multiple columns without validation, you can use the update_columns
method.
# Find the records you want to update
posts = Post.where(published: true)
# Update multiple columns without validation
posts.update_columns(title: "New Title", body: "New Body")
The update_columns
method also bypasses all validations and callbacks, but unlike update_column
, it updates multiple columns at once. This method is useful when you need to update many records at once.
update_attributes
MethodThe update_attributes
method is similar to update_columns
, but it checks for validation errors before saving the records.
# Find the records you want to update
posts = Post.where(published: true)
# Update multiple columns with validation
posts.update_attributes(title: "New Title", body: "New Body")
If any of the records fail validation, the method will raise an ActiveRecord::RecordInvalid
exception, and the update will not be saved. This method is useful when you need to update multiple records with validation but don't want to run callbacks.
In this tutorial, we have seen three ways to update records without activating validations in Rails. We have explored the update_column
, update_columns
, and update_attributes
methods, and seen how they can be used to bypass validations and callbacks during updates.
Remember that updating records without validation should only be done when necessary and with caution, as it can lead to data inconsistencies and other problems.