Before_validation:更新并保持连续性
我有一个简单的工作时间表 Rails 应用程序。计划中的作业将按作业的优先级排序。由于某些作业的优先级可能会发生变化,并且出于相同的性质,它们需要完成的顺序也可能会发生变化,因此我需要能够更新优先级以及表中其余部分的优先级,以确保没有两个作业共享相同的优先级。一旦更新优先级,我希望它使优先级列表是连续的,换句话说,优先级被标记为1、2、3、4、5等。而不是像 1、2、4、5、6、8 等那样有间隙。
有人可以帮我找出实现此目标的正确编码吗?
这就是我当前模型中的内容:
class Job < ActiveRecord::Base
include ActiveModel::Dirty
belongs_to :customer
has_many :job_items
before_validation :update_priorities
validates :priority, :uniqueness => true
private
def update_priorities
if self.priority_changed?
self.class.where("priority >= ?", self.priority).update_all("priority = priority + 1")
else
nil
end
end
如果是一项全新的工作,上面的代码会很好地更新优先级。然而,一旦我开始重新排序当前的作业,序列中就会开始出现间隙。
我目前使用的是Rails 3.2.1
I have a simple work schedule rails app. The jobs in the schedule will be ordered by the priority of the job. Since some jobs may change in priority, and by the same nature, order they need to be completed, i need to be able to update the priority and the priority of the rest of the table to ensure no 2 jobs share the same priority. Once the priority is updated, i want it to make that the list of priorities is continuous, in other words, the priorities are labeled 1,2,3,4,5,etc. instead of having gaps like 1,2,4,5,6,8,etc.
Can someone help me figure out the proper coding to achieve this?
This is what i currently have in my model:
class Job < ActiveRecord::Base
include ActiveModel::Dirty
belongs_to :customer
has_many :job_items
before_validation :update_priorities
validates :priority, :uniqueness => true
private
def update_priorities
if self.priority_changed?
self.class.where("priority >= ?", self.priority).update_all("priority = priority + 1")
else
nil
end
end
The above code updates the priorities fine if its a brand new job. However, once i start to re-order the current jobs, gaps begin to appear in the sequence.
I am currently using Rails 3.2.1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(2)
我尝试了 Veraticus 提供的acts_as_list,但它对我的应用程序无法正常工作。经过一番摆弄后,我将代码更改为以下内容,它的工作原理就像我需要的那样。
def update_priorities
if self.priority_changed?
if self.priority < self.priority_was
self.class.where("priority >= ?", self.priority).update_all("priority = priority + 1")
self.class.where("priority > ?", self.priority_was).update_all("priority = priority - 1")
else
nil
end
if self.priority > self.priority_was
self.class.where("priority <= ?", self.priority).update_all("priority = priority - 1")
self.class.where("priority < ?", self.priority_was).update_all("priority = priority + 1")
else
nil
end
end
结尾
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
您可能在这里寻找的是 acts_as_list,它会自动为您执行此类操作。例如,如果您正在创建一个新工作并且想要为其指定一个职位:
要查看acts_as_list为您提供的所有方法,查看源代码中的注释。
What you're probably looking for here is acts_as_list, which will automatically do this sort of thing for you. For example, if you're creating a new job and you want a certain position for it:
To see all the methods acts_as_list provides you, check out the comments in the source.