2010-10-08 44 views
1

假設我有一個按名爲sibling_order的列排序的頁面集合。是否有更新集合的順序如下比我在做什麼更有效的方式:是否有更有效的方法來更新Rails 3中對象集合的順序?

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 

回答

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 
+0

感謝您的答覆。但是,使用sanitize_sql_array不斷拋出一個NoMethodError。我最終得到它使用插值工作。這樣做有缺點嗎? – 2010-10-09 16:20:41

+0

更新了答案,現在它應該可以工作。清理SQL是一種更好的做法。 – 2010-10-09 16:50:31

+0

謝謝!最後我知道如何使用sanitize_sql_array :) – 2011-03-15 05:53:33

相關問題