简体   繁体   English

记录更新将更新模型中的所有其他记录,并在Rails 3.1中进行全局排序

[英]Update on record would update all other records in model, global ordering in rails 3.1

I would like to update all records in a rails (3.1) model when i update an attribute on a single record. 当我更新单个记录上的属性时,我想更新Rails(3.1)模型中的所有记录。

Like self.update_attribute(:global_order => 1) then before or after save a would like to update all other records to update thier global_order (1, 2, 3, 4). 就像self.update_attribute(:global_order => 1)一样,保存之前或之后想要更新所有其他记录以更新global_order(1、2、3、4)。

Right now with on after_save callback I get caught in a recursive loop, is skip callbacks the way to go? 现在,在after_save回调中,我陷入了递归循环中,跳过回调是路要走吗? I would like the app to throw exceptions if anything seems strange in global_order. 如果global_order中出现任何异常,我希望该应用程序引发异常。

Or are there any 3.1 gems that would solve my issue. 还是有任何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

Not sure if there's a gem, but you could definitely refactor this with the following considerations: 不确定是否有宝石,但是您绝对可以通过以下考虑因素进行重构:

  • No need to pollute the object with an instance variable when a local one will do 当本地变量需要执行时,无需使用实例变量污染对象
  • The first three lines are sorting the same set, why not do that once? 前三行对同一集合进行排序,为什么不一次执行呢?

... ...

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM