Question

Currently going through the famous tutorial. Having a hard time understanding why the update_attribute method bypasses model validations. Am I correct when I assume update_attributes is subject to validations and update_attribute is not?

Helper:

module SessionsHelper

  def sign_in(user)
    remember_token = User.new_remember_token
    cookies.permanent[:remember_token] = remember_token
    user.update_attribute(:remember_token, User.hash(remember_token))
    self.current_user = user
   end
 end

Validations:

class User < ActiveRecord::Base
  has_secure_password
  before_create :create_remember_token
  before_save { self.email = email.downcase }
  validates :name,      presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(?:\.[a-z\d\-]+)*\.[a-z]+\z/i
      validates :email,     presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness:    { case_sensitive: false }
  validates :password, length: { minimum: 6 }
Was it helpful?

Solution

From Rails base references itself, it is known that:

update_attribute updates a single attribute and saves the record without going through the normal validation procedure. This is especially useful for boolean flags on existing records.

See, http://apidock.com/rails/ActiveRecord/Base/update_attribute.

and if you want to know why it gets bypassed, the look in to the below SO answer:

Rails: update_attribute vs update_attributes

Hope it helps :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top