Let's simplify the case to assume the current_user who'll sort this list is the only man who can save the order to db.
In this case you need one extra field in Link
to save the changed sequence. Let's name it seq
. It will be the major method to order the links.
Then, for jQuery part, I find toArray would be simple to use, instead of current 'serialize'
, with others untouched.
The jQuery ajax will post to sort
method in controller. And the params[:links]
(I'm not sure about the key, just assume it's links
) will be an array of ids.
# GroupsController
def sort
ids = params[:links]
ids.each_with_index do |id, index|
link = Link.find(id)
link.seq = index
link.save
end
end
# Then always ship links with order of seq
def show
group = Group.find(params[:id])
@links = group.links.order('seq ASC')
end
Just a note that my implementation sort
method is not efficient that there are multiple queries executed. A better approach would be construct custom sQL to update in a batch. This is just a quick answer to present the idea.