How to Skip Validations When Updating in Rails

Rails provides several methods to update records, but one that stands out for its simplicity and efficiency is update_attribute.

What does update_attribute do?

The Problem

Imagine you have a Rails model with a validation that ensures a value must always be greater than zero:

1
2
3
class Product < ApplicationRecord
  validates :stock, numericality: { greater_than: 0 }
end

This validation is critical for the system’s functionality but there’s a specific case where you need to set stock to 0 for a certain product. Directly attempting to update the value will trigger the validation error:

1
2
product = Product.find(1)
product.update(stock: 0) # This will fail due to the validation

To bypass validations, you can use the update_attribute method. Here’s how:

1
2
product = Product.find(1)
product.update_attribute(:stock, 0)

Cautions

In conclusion, update_attribute is a powerful tool in your Rails toolkit, offering a quick and efficient way to update a single attribute. However, its bypass of validations means it should be used with care. Understanding its strengths and limitations will help you make informed decisions about when to use it.