mgerstenblatt-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org
2010-Oct-08 23:02 UTC
Is there a more efficient way to update the order of a collection of objects in rails 3?
Suppose I have a collection of Pages that are ordered by a column called :sibling_order. Is there a more efficient way to update the ordering of the collection than what I''m doing below: 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 -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
Colin Law
2010-Oct-09 07:48 UTC
Re: Is there a more efficient way to update the order of a collection of objects in rails 3?
On 9 October 2010 00:02, mgerstenblatt-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org <mgerstenblatt-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:> Suppose I have a collection of Pages that are ordered by a column called > :sibling_order. Is there a more efficient way to update the ordering of the > collection than what I''m doing below:Have a look at acts_as_list. Even if you do not want to use it (but why re-invent the wheel) then examining the code may be useful. Colin -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.