Find_each with custom ordering in Rails


Rails Development

In a recent project of mine I had to implement an activity feed. I have been meaning to try out the proposed solution by GiveGab which was a response to ThoughtBot's approach. I especially liked GiveGab's elegant solution to address the issues ThoughtBot had with the fan out on read approach by using Enumerations with findeachin_batches in the background to do the heavy-lifting in the database.

However, what GiveGab seems to have missed is that Rails ignores the ordering of the ActiveRecord::Relation when using findeach/findeachinbatches. It does so for consistency purposes by sorting on the primary key to avoid the change of ordering because of new records or updated records.

I have found ar-as-batches by telent which tried to remedy the situation by giving you responsibility over your query, however I felt it wasn't generalized enough and using offsets to batch does not prevent the issue of inconsistency when inserting new records.

Hence, I quickly wrote ar-find-in-batches-with-order to give you the option of using batched finds with a custom ordering. It's a bit verbose on the options side, but believe gives you great flexibility and ultimately makes GiveGab's solution workable.

Let me know what you think, I'm still just getting started with open-sourcing stuff.

comments powered by Disqus