简体   繁体   中英

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.

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).

Right now with on after_save callback I get caught in a recursive loop, is skip callbacks the way to go? I would like the app to throw exceptions if anything seems strange in global_order.

Or are there any 3.1 gems that would solve my issue.

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

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.

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