updating a model while in before_update

I've been wondering, suppose I have a model with an attribute that in every instance is dependent on that same attribute in other instances. The best example for this would be an order attribute for items in a list.

The best place to update the rest of the items' order attributes would be in a before_update callback method, were you have both the item's old and new values.

But now whenever you update the other items in the list the callback is going to be called again, and again...

I'm looking for an elegant way of solving this.

I have heard about the :update_without_callbacks method, but i don't want to use a private method, and also i feel like adding extra attributes would be unnecessary.

Got any good ideas? Thanks in advance!

Answers


One way would be to use update_all to set the order of all the other items in bulk.

That way you would efficiently limit the number of queries to one and prevent any callbacks from being triggered.

https://github.com/rails/rails/blob/83e42d52e37a33682fcac856330fd5d06e5a529c/activerecord/lib/active_record/relation.rb#L274


I feel the fact that you have to do this type of update across entries suggests you haven't properly conceptualized your problem. Why not create a List model that has the order attribute, and then create a one-to-many relationship between the List model and the Item model. This way, there's only one place to update the ordering information and no need for complicated and brittle callbacks.


Need Your Help

How to compare elements in an array (javascript)

javascript arrays compare

Apologies if this sounds very basic but I'm a total novice when it comes to coding (I'm trying my best to get better though!)

How to set a the role type text in the .Net Role Provider?

c# asp.net-mvc asp.net-mvc-4 entity-framework-5 role-manager

In my UserController.Login action, I am trying to AddUserToRole() for an authenticated user, with the value of one of the user entity's MembershipType.MembershipName navigation property: