0bserver07
0bserver07

Reputation: 3471

How to update model attribute from Model?

I have a method to change user status inside the it's model, is it possible to use this do something like this inside the user model:

class User < ActiveRecord::Base

def confirm!
  super
  self.update_column(:status => "active")
end

end

I saw these two examples;

Rails update_attribute

how to update attributes in self model rails

couldn't quite get which one to go with!

Upvotes: 0

Views: 199

Answers (1)

infused
infused

Reputation: 24337

It depends on whether or not you want any validations in the model to run. update_attribute will not run the validations, but update_attributes will. Here are a couple of examples.

Using update_attributes:

class User < ActiveRecord::Base
  validates :email, presence: true

  def confirm!
    update_attributes(status: 'active')
  end
end

The following will return false and will not update the record, because not email has been set:

user = User.new
user.confirm! # returns false

Using update_attribute:

class User < ActiveRecord::Base
  validates :email, presence: true

  def confirm!
    update_attribute(:status, 'active')
  end
end

The following will update status to active regardless of whether or not email has been set:

user = User.new
user.confirm! # returns true

Upvotes: 2

Related Questions