简体   繁体   English

如何在Rails中分配优先级(一种优先级队列)?

[英]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). 假设我有一张名为power-ups的表(我将以游戏为例)。

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). 因此,当用户第一次登录时,他获得最低功耗(优先级为0的功能)。 When a user passes a level, he gets the next level power-up (priority 1). 当用户通过一个级别时,他将获得下一级别的上电(优先级为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. 最直接的方法是使用一个名为Priority的字段,可以在admin表中手动分配给0,1,2 ....并且将按顺序给出加电。

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? 有更简单的方法吗?

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 检查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 这会将用户提升到second_state

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM