Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Batch setting of position #112

Closed
jrdaniels opened this issue Mar 20, 2014 · 2 comments
Closed

Batch setting of position #112

jrdaniels opened this issue Mar 20, 2014 · 2 comments

Comments

@jrdaniels
Copy link

I have a issue when trying to batch assign the position of elements in a list, and then when the items are saved, the order gets duplicated in the middle of the list.

I have a category model, a product model, and a category_product_mappings model. Acts as list is on the mapping model to manage the order of the products in the category.

The category model has:
accepts_nested_attributes_for :category_product_mappings, allow_destroy: true

In the edit view for the category, the user can change the order of the products. We use js on the client to renumber the products on the moves, updating the hidden position field for the mappings fields.

When we submit the edit form, the category.update_attributes will update all the mapping objects correctly, and then save them. When the save occurs, acts_as_list will trigger it's own resequencing due to the callback:

after_update :update_positions

This will throw off the ordering as shown below
Original Order:
Prod1: 0
Prod2: 1
Prod3: 2
Prod4: 3
Prod5: 4
Prod6: 5
Prod7: 6
Prod8: 7
Prod9: 8
Prod10: 9

after reversing the order of the products and saving the position is:

Prod10: 0
Prod9: 1
Prod8: 2
Prod7: 3
Prod6: 3
Prod5: 4
Prod4: 6
Prod3: 7
Prod2: 8
Prod1: 9

Is seems when we get to the middle of the list, the shuffle_positions_on_intermediate_items call doesn't like what I have done with the position elements by setting them directly through accepts_nested_attributes.

Any thoughts on how I can get around this?

@jrdaniels
Copy link
Author

Circling back around on this to see if there was anyone who knows a way around the batch assign problem.

@brendon
Copy link
Owner

brendon commented Apr 17, 2016

I'm not sure, but I think your most likely option would be to bypass the callbacks with something like this:

product_ids.each_with_index do |id, index|
    Product.update_all(['position=?', index+1], ['id=?', id])
end

It accepts an array of ids and updates their position according to the position of that id in the array. You'd want to scope Products correctly too to ensure the user can't update willy nilly.

I'm going to close this now since it's so old, do feel free to ask questions :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants