Reputation: 155
I am trying to understand how to activate and deactivate a certain Model in rails without necessarily deleting anything.
Came across this code.
class User < ActiveRecord::Base
def activate_account!
update_attribute :is_active, true
end
def deactivate_account!
update_attribute :is_active, false
end
end
I understand for the User model, there is a "is_active" column.
My question is how does this boolean actually cause the object to be activated and deactivated.
I mean is the "is_active" an actually Rails method? or is it defined somewhere else? Can't seem to get how the "magic of activation/deactivation" happens when the column is set to either true or false.
Upvotes: 0
Views: 1791
Reputation: 862
To elaborate on Florrent Ferry's very correct answer, the code you gave as an example are two methods inside the model.
You would call this on your model, for example: current_user.deactivate_account!
this would call the method on the current_user
, and update the is_active
column in their account to false
.
So, you could achieve something similar with comments, by replicating the methods into your Comment model, and then calling the methods on that particular comment. eg: @comment.deactivate_comment!
this would set the boolean on that comment to false.
Now, it would still show up if you were using something like @comments = Comment.all
in your controller, and then looping through @comments
in your view. Because it still exists, so ALL will pull it out. But, by scoping the @comments
instance, you can only gather the comments where it active is true.
You can do this directly in the controller using:
@comments = Comment.where(is_active: true)
But it would be better to scope this as Florrent pointed out. eg, in your model you would set up the scope:
scope :active, -> { where(is_active: true) }
Then in your controller you can simply call
@comment = Comment.all.active
Upvotes: 1