Peter Nguyen
Peter Nguyen

Reputation: 359

How to write method for auto update one column based on the other column in the same row rails

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

Answers (1)

Max Williams
Max Williams

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

Related Questions