Reputation: 3471
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;
how to update attributes in self model rails
couldn't quite get which one to go with!
Upvotes: 0
Views: 199
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