Victor Ronin
Victor Ronin

Reputation: 23268

Looking for nice RoR way to correctly validate a state of a record

I have a model and a column of this model represents a state . It's numeric value and it could be 1,2,3.

I have two concerns:

a) Based on the business logic, the state can only go from 1 to 2 and from 2 to 3. It can't go back from higher numbers to lower number and it can't just from 1 to 3 in one step.

b) I don't want to expose these numbers to controllers (don't like magical numbers flying around).

I did following

However, I feel that's more Java/C++ way (which is my background) - 6 methods to do one thing.

Is there any better way to accomplish this in RoR?

Upvotes: 0

Views: 51

Answers (2)

Carson Cole
Carson Cole

Reputation: 4451

How about this:

class Something < ActiveRecord::Base
  before_create :check_state


  private

  def check_state
    if state_changed?
      if state_was == 1 && state != 2
        self.errors.add(:state, "some message")
      elsif state_was == 2 && state != 3
        self.errors.add(:state, "some message")
      else
        self.errors.add(:state, "some message")
      end
    end
  end

end

Upvotes: 0

robbrit
robbrit

Reputation: 17960

Not sure if this is still the best way to do it (my Rails is a little rusty) but there is a gem called acts_as_state_machine which I think will do exactly what you want.

Upvotes: 1

Related Questions