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
I tried the acts_as_list provided by Veraticus, but it just wasn’t working properly for my application. After some fiddling with it, i changed my code to the following and it works just like i need it to.
end