[英]Update on record would update all other records in model, global ordering in rails 3.1
當我更新單個記錄上的屬性時,我想更新Rails(3.1)模型中的所有記錄。
就像self.update_attribute(:global_order => 1)一樣,保存之前或之后想要更新所有其他記錄以更新global_order(1、2、3、4)。
現在,在after_save回調中,我陷入了遞歸循環中,跳過回調是路要走嗎? 如果global_order中出現任何異常,我希望該應用程序引發異常。
還是有任何3.1寶石可以解決我的問題。
after_save :set_global_order
def set_global_order
@products = self.class.all(:order => :global_order)
@products.sort! {|a,b| a.global_order <=> b.global_order}
@products.reverse!
@products.each_with_index do |p, index|
p.update_attributes!({:global_order => index + 1})
end
end
不確定是否有寶石,但是您絕對可以通過以下考慮因素進行重構:
...
def set_global_order
products = self.class.order('global_order DESC')
products.each_with_index do |p, index|
p.update_column(:global_order, index + 1)
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.