Rails and Stuff at Abel killed Cain

Ruby on Rails and other Webdevelopment

This is more like a rather small hint, describing how to make tables sortable in rails.

Just like ryan bates shows in his rails casts, there is a similar way to sort tables, instead of lists.

Here the example-code how to make the tables sortable:

1
2
3
4
5
6
7
8
9
10
- # this is haml-code! can be done in erb as well..
%table
  %tbody{:id=>"products"}
    -for product in @products
      %tr{:id=>"product_#{product.id}"}
        %td=product.name
        -#.. more hamlcode
        -# i want a drag-handler, optional
        %td.drag_handle
          =image_tag "move.gif"

Note: NOT the table has the id, the tbody has, its the actualy tr-s parentnode, ever!
This code actually only builds the table – important is the id setting of each tr and tbody.

after the table, just add this simple piece:

1
= sortable_element('products', :url => {:action => 'update_order'}, :handle => :drag_handle, :tag => :tr)

Note: the :tag symbol now points to the tr, default is li.

So far, saving the sorted rows is just like railscasts shows:

1
2
3
4
5
6
7
8
9
10
11
# routes.rb
# currently in admin-namespace..
admin.resources :products, :collection=>{:update_order => :post}

# product_controller
def update_order
    params[:products].each_with_index { |id,index|
      Product.update_all(['position=?', index], ['id=?', id])
    }
    render :nothing=>true
end

Dont forget to include scriptacolous in your layouts.
Hope this helps anyone!

Original Podcast by Ryan Bates:
Sortable Lists

Write a Comment