I wanted to use the gem acts_as_list to reorder lists.
But it doesn't seem to handle more restricted queries than association-based (I want to order lists based both on an association AND objects with an boolean attribute set to true
).
If I'm not mistaken, by watching the logs it seems like the gem is using a SQL statement that updates many records at the same time.
I would like to use the exact same statements to factor my own custom ordering code.
These two following statements are moving a question object from position 3 to 8.
UPDATE "questions" SET position = (position - 1) WHERE ("questions"."question_list_id" = 2 AND position > 3 AND position <= 8)
UPDATE "questions" SET "position" = ?, "updated_at" = ? WHERE "questions"."id" = 55 [["position", 8], ["updated_at", "2014-06-09 14:40:47.545040"]]
Is it possible with ActiveRecord or any other way, and if so how, to reuse the above code?
You can mix SQL and ActiveRecord to achieve these SQL statements. They can be written:
Question.where(question_list_id: 2, position: [4..8]).update_all('position = (position - 1)')
Question.update(55, position: 8)
The act_as_list gem is not responsible for sorting the elements, it just keeps in DB the position of the elements. It's up to you to sort the elements with the API provided by act_as_list.
Also there's a scope
option if you want to target only some elements. See source.