简体   繁体   English

Rails:模型的自定义订购和优先级

[英]Rails: Custom ordering and priority for model

For a Rails project I am working on, I have a model that has an image and a priority attached to it. 对于我正在从事的Rails项目,我有一个模型,该模型具有图像和优先级。 So it looks something like this: 所以看起来像这样:

card: 
  -id 
  -name
  -img_url
  -priority

The priority is a number where 1 is the highest priority (default) and it goes on to 2, 3, etc. priority是一个数字,其中1是最高优先级(默认值),然后继续为2、3等。

My question is what is the best way to assign these priorities on creation? 我的问题是在创建时分配这些优先级的最佳方法是什么? Should I keep a variable in the controller that keeps track of the priorities assigned already and assigns the next one? 我是否应该在控制器中保留一个变量,以跟踪已经分配的优先级并分配下一个优先级? Also, these priorities are like to change ie the card with priority 3 changes to 1 and so 1 must become 2, and 2 must become 3. 同样,这些优先级也想更改,即优先级3的卡更改为1,因此1必须变为2,而2必须变为3。

What's the best way to deal with this? 处理此问题的最佳方法是什么?

you can find last number and then add it and check 您可以找到最后一个号码,然后添加并检查

def create
  @card = Card.new(params...)
  @last_card = Card.last
  priority = @last_card.priority
  if priority == 3 
    next_priority = 1
  else
    next_priority = priority + 1
  end
  @card.priority = next_priority
end 

I would suggest to take priority management operation to DB and DB trigger is a good solution. 我建议对数据库进行优先级管理操作,并且数据库触发器是一个很好的解决方案。

First set unique constraint the priority column to make sure another thread cannot insert same next priority number. 首先在priority列中设置唯一约束,以确保另一个线程不能插入相同的下一个优先级号。 You can use max function to get the next number. 您可以使用max函数获取下一个数字。

And when priority changes, you change priority of all rows one by one which will be resource intensive operation if done in the rails. 并且当优先级更改时,您将一一更改所有行的优先级,如果在rails中完成,这将占用大量资源。

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

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