Reputation: 359
I have a Users table like this:
-----------------------------------------------
| name | email | role | card_amount (integer) |
-----------------------------------------------
| ... | ... | ... | ... |
-----------------------------------------------
I want to update the role column based on the card_amount column automatically with a specific condition like below:
if @user.card_amount >= 100
Then the role column will auto update like:
@user.role = "buyer"
How to make it happens automatically? So everytime the @user.card_amount >= 100 the role colum will have value "buyer".
Or when I go to rails console and update the card_amount to 100, then the role column will also being updated to "buyer"?
Upvotes: 0
Views: 167
Reputation: 32955
You should use a before_save
callback. eg
before_save :update_role
def update_role
if self.card_amount >= 100
self.role = "buyer"
end
end
Read this: http://guides.rubyonrails.org/active_record_callbacks.html
Upvotes: 2