geekchic
geekchic

Reputation: 2431

How to assign priorities (a kind of priority queue) in Rails?

Let's say I have a table called power-ups (I'm going with a gaming example).

I need the power-ups to be assigned to users on the basis of their 'priorities'.

So the first time a user logs in, he gets the lowest power-up (the one with priority 0). When a user passes a level, he gets the next level power-up (priority 1).

The most straightforward way of doing this would be to have a field called Priority, which can be manually assigned to 0, 1, 2.... in the admin table and the power-ups would be given in that order.

Pseudo-code for what I have in mind, hope it helps:

if (level == 0) 
   find power_up where priority == 0
else if (level == 1)
   find power_up where priority == 1
..................

Is there a simpler way of doing this?

Upvotes: 1

Views: 735

Answers (1)

xlembouras
xlembouras

Reputation: 8295

If all you want is a simple level for the user, a plain integer attribute will do the job.

I think you are trying to describe here some sort of state machine functionality.

check the aasm gem

you can have something like:

class User
  include AASM

  aasm do
    state :first_state, :initial => true
    state :second_state
    state :third_state
    ...
    state :final_state

    event :first_blood do
      transitions :from => :first_state, :to => :second_state
    end

  end
end

with which you can do things like

user.first_blood

which will promote the user to the second_state

Upvotes: 3

Related Questions