itmammoth / rails_sortable

Easy drag & drop sorting with persisting the arranged order for rails
MIT License
142 stars 37 forks source link

How to make newly added items appear first? #60

Open skillmatic-co opened 1 year ago

skillmatic-co commented 1 year ago

In my app, after you've sorted already, and when you add a new item to the list of items that being pulled for rails_sortable, it's added to the end of the list instead of first.

Is there a way for this gem to automatically make newly added database items appear first (have sort = 1)?

itmammoth commented 1 year ago

I am not entirely sure of the situation, could you please show me with the code?

skillmatic-co commented 1 year ago

Well you can see in max_sort that it's setting newly created items to have a max_sort, not 1. To me, this should be an option - to have newly created items default to a sort value of 1 or a sort value of max_sort.

Let's say I have 50 items, and they are sorted 1-50. Now let's say I add a new item. I don't necessarily always want that new item to have a sort value of 51. I would like it to have a sort value of 1 (so it's added to the beginning when ordering by the sort value). Then of course every other object would have to get +1 added to their sort value.

Since I've created this issue, I've already found a workaround with something like this:

after_create :update_sort

def update_sort     
  self.sort = 1
  self.save!
  Product.where.not(id: self.id).each do |p|
    p.update(sort: p.sort + 1)
  end
end

But I think this should be built into the gem.