pawciorr
pawciorr

Reputation: 43

How to update one column depending on the value of second column in Rails

I am building a small, language-learning app in Rails and have following problem. A model 'Flashcard' has two integer values in the database: 'counter' and 'level'.

Counter indicates how many times a flashcard was seen. Level depends on the counter, for instance:

if the counter is between 0 and 10, the level should be 1,

if the counter is between 11 and 20, counter should be 2 and so on.

My question is: how to update one column of the table depending on value from the other?

I could probably use series of if statements or case statement but perhaps there is an easier way to set all this in Model.

Thanks in advance.

Upvotes: 0

Views: 566

Answers (2)

Mark
Mark

Reputation: 71

Override your "counter=" method in a way that it will set the level. Using the "super" method will update your counter normally without changing the method. For the level try using math to set it automatically based on the value of counter.

def counter=(value)
  self.level = [(value - 1) / 10 + 1, 1].max
  super
end

Upvotes: 1

jvillian
jvillian

Reputation: 20263

Why even use a level field? Just have a level method that returns a value based on the counter field. Something, perhaps, along the lines of:

class Flashcard < ActiveRecord::Base

  def level
    ([counter-1,0].max/10)+1
  end

end

Upvotes: 0

Related Questions