Reputation: 4429
I'm stuck with this problem. I;ve built an API in Rails and a client in Angular. I've got a model called Todo
which has a property called order
. When I create a new Todo, I automatically assign the newly created todo a value order like so:
@todo = Todo.create(todo_params)
@todo.order = Todo.count + 1
And to display all todos:
@todos = Todo.where(...).order(:order.desc)
In my client I'm using Sortable for the UI manipulation and there's a method called onUpdate
which gives me the new indexes for the array.
The problem I'm having is that the indexes are considerably different than the value I've in the order
property. When the aforementioned function is called I get the item and two more values: newIndex
and oldIndex
, but the problem is that this doesn't give me the index of the other todos, so how can I reorganise this on the database?
I'd appreciate any help as I'm a bit at loss here.
PS: Please note this is Rails API only, so no views.
EDIT
Output wanted:
Let's imagine this: I have three items in the database: {name: A, order: 1}, {name: B, order: 2}, {name: C, order: 3}
. In the front-end, while using ng-repeat, each item will have an $index
. Let's say for argument sake that A will have $index
value of 0, B 1, C 2. At the moment, when I use the Angular library Sortable, when I manually sort the list, I get the values: oldIndex
and newIndex
which corresponds to the position of the item I've moved within the array, but it does not shows the position of all items within array, so I don't know how to use the properties these values to update the object in the database.
Upvotes: 0
Views: 296
Reputation: 4429
For anyone that might be interested: At the end I've used the following solution:
Every time Sortable
updated an item, it also sends an array with all items on it in the correct order. I then looped through the array and updated each item with the new order. Not sure this is the most efficient way to do it but it resolved the problem for now.
Upvotes: 0