def positioning
tasks = Painting.all.order(:position)
increment = false
tasks.each do |t|
if !increment && t.position == self.position
increment = true
t.position += 1
t.save
elsif increment
t.position += 1
t.save
end
end
end
This method is for a before_save
callback, and works when I add a new painting, but it's doing something wrong incrementing the other objects position and later when I want to update any object this is a problem.
Version 1 using update_attribute
paintings = Painting.where(:position >=self.position)
paintings.each do |painting|
painting.update_attributes(:position, painting.position + 1)
end
Version 2 using hash
paintings = Painting.where(:position >=self.position)
paintings.each do |painting|
paintingHash = Hash.new
paintingHash["position"]=painting.position+1
painting.update(paintingHash)
end
The description is for version 2
line 1 find all paintings with position higher than current
line 2 start an itteration through the selected paintings
line 3 create new hash used for updating
line 4 assign value to a variable in the hash equaling to origional position +1
line 5 execute update
line 6 end he iteration
Try this?
def positioning
tasks = Painting.all.order(:position)
increment = false
tasks[self.position..-1].each do |t|
t.position += 1
t.save
end
end
This allows you to effectively loop through only the ones you want to increment. Since you already have all the tasks in hand from the first line, this doesn't cost anything more that I can tell.
I'm also not entirely sure if your position is 0 based or 1 based. my code assumes 0 based but if not you'll need to tweak that indexing line.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.