ranked-model icon indicating copy to clipboard operation
ranked-model copied to clipboard

Failing to explicitly set position can lead to reordering on update

Open CodingAnarchy opened this issue 1 year ago • 2 comments

Having a record that is not set to a position defaults to :last, but this causes the record to inadvertently be moved to the last position whenever there is an update to the already saved record.

Specifically, this case will give an odd result:

class Foo < ActiveRecord::Base
    include RankedModel
    
    ranks :row_order
end

r = Foo.create()
other = Foo.create()
r.update(some_field: "new_value") # <= This line will also update the row_order field

This same behavior does not occur if you fetch the record from the database directly - the row_order will be static in that case.

I ran into this issue with some usage of the pattern in tests to create the object, then update it, reload, and verify the ordering.

CodingAnarchy avatar Nov 16 '22 04:11 CodingAnarchy

That's interesting. I guess it's a downside of the underlying database state changing at save but not being updated in the object itself. I'm not sure what the answer is here. Did you want to explore a PR around populating the row_order on save if it's inferred?

brendon avatar Nov 16 '22 09:11 brendon

@brendon I can definitely look into it, sure.

CodingAnarchy avatar Nov 17 '22 01:11 CodingAnarchy