假设我有一个由名为:sibling_order的列排序的Pages集合。是否有一种更有效的方式来更新集合的顺序,而不是我在下面所做的:
class Page < ActiveRecord::Base
...
def update_order(order)
if (order < self.sibling_order)
siblings = Page.where("parent_id = ? AND sibling_order < ? AND sibling_order >= ?",new_parent_id,self.sibling_order,order)
siblings.collect{|s|s.update_attribute(:sibling_order,s.sibling_order + 1)}
elsif (order > self.sibling_order)
siblings = Page.where("parent_id = ? AND sibling_order > ? AND sibling_order <= ?",new_parent_id,self.sibling_order,order)
siblings.collect{|s|s.update_attribute(:sibling_order,s.sibling_order - 1)}
end
self.update_attribute(:sibling_order, order) if self.sibling_order != order
end
...
end
答案 0 :(得分:1)
试试这个:
def update_order(order)
k = (order < self.sibling_order) ? 1 : -1
sql = "parent_id = ? AND " + ( k == 1 ?
"sibling_order < ? AND sibling_order >= ?" :
"sibling_order > ? AND sibling_order <= ?")
sql = Page.send(:sanitize_sql_array, [sql, new_parent_id, sibling_order,order])
Page.update_all("sibling_order = sibling_order + (#{k})", sql)
self.update_attribute(:sibling_order, order) if self.sibling_order != order
end