#147 Sortable Lists
Creating drag & drop sortable lists is fairly easy using Prototype and the built in helper methods. See how in this episode.
- Download:
- source codeProject Files in Zip (106 KB)
- mp4Full Size H.264 Video (12 MB)
- m4vSmaller H.264 Video (8.34 MB)
- webmFull Size VP8 Video (20.2 MB)
- ogvFull Size Theora Video (14.6 MB)
There is a newer version of this episode, see the revised episode.
Resources
bash
script/generate migration add_position_to_faqs position:integer
rake db:migrate
script/plugin install git://github.com/rails/acts_as_list.git
script/generate migration add_position_to_faqs position:integer rake db:migrate script/plugin install git://github.com/rails/acts_as_list.git
routes.rb
map.resources :faqs, :collection => { :sort => :post }
map.resources :faqs, :collection => { :sort => :post }
faqs_controller.rb
def sort
params[:faqs].each_with_index do |id, index|
Faq.update_all(['position=?', index+1], ['id=?', id])
end
render :nothing => true
end
def sort params[:faqs].each_with_index do |id, index| Faq.update_all(['position=?', index+1], ['id=?', id]) end render :nothing => true end
models/faq.rb
class Faq < ActiveRecord::Base
acts_as_list
end
class Faq < ActiveRecord::Base acts_as_list end
layouts/application.html.erb
<%= javascript_include_tag :defaults %>
<%= javascript_include_tag :defaults %>
faqs/index.html.erb
<ul id="faqs">
<% for faq in @faqs %>
<% content_tag_for :li, faq do %>
<span class="handle">[drag]</span>
<%= link_to h(faq.question), faq %>
<% end %>
<% end %>
</ul>
<%= sortable_element("faqs", :url => sort_faqs_path, :handle => "handle") %>
<ul id="faqs"> <% for faq in @faqs %> <% content_tag_for :li, faq do %> <span class="handle">[drag]</span> <%= link_to h(faq.question), faq %> <% end %> <% end %> </ul> <%= sortable_element("faqs", :url => sort_faqs_path, :handle => "handle") %>
css
li .handle {
font-size: 12px;
cursor: move;
color: #777;
}
li .handle { font-size: 12px; cursor: move; color: #777; }

