Skip to content

Instantly share code, notes, and snippets.

@benwoodward
Created August 25, 2012 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benwoodward/3465323 to your computer and use it in GitHub Desktop.
Save benwoodward/3465323 to your computer and use it in GitHub Desktop.
Ruby on Rails Sortable/Reorderable lists on STI models using ranked_model, Twitter Bootstrap and inherited_resources
%h1= "Listing " + "#{resource_name}s"
.btn-group.pull-right
= link_to "All #{resource_name(item: resource_class.superclass)}s", polymorphic_path([:admin, resource_class.superclass]), class: 'btn'
= link_to "Add #{resource_name}", new_resource_path, class: 'btn-primary btn'
%br
%br
%table.table.table-bordered.table-striped#sortable{:data => {update_url: polymorphic_path([:sort, :admin, resource_class])}}
%thead
%tr
- attributes.each do |attr|
%th= resource_class.human_attribute_name(attr)
%th  
%tbody
- collection.each do |resource|
%tr{data: {item_id: "#{resource.id}"}, class: 'item'}
- attributes.each do |attr|
%td= resource.public_send(attr).to_s.truncate(20)
%td
= link_to 'show', resource_path(resource), :class => 'btn'
= link_to 'edit', edit_resource_path(resource), :class => 'btn btn-primary'
= link_to 'destroy', resource_path(resource), method: :delete, confirm: "Are you sure?", :class => 'btn btn-danger'
#sortable {
tr {
cursor: row-resize;
}
}
jQuery ->
#this is a fix; when a tr is dragged with jQuery UI sortable
#the cells lose their width
cells = $('.table').find('tr')[0].cells.length
desired_width = 940 / cells + 'px'
$('.table td').css('width', desired_width)
$('#sortable').sortable(
axis: 'y'
items: 'tr'
stop: (e, ui) ->
ui.item.children('td').effect('highlight', {}, 1000)
update: (e, ui) ->
item_id = ui.item.data('item_id')
position = ui.item.index()
$.ajax(
type: 'POST'
url: $(this).data('update_url')
dataType: 'json'
data: { id: item_id, menu_item: { row_order_position: position } }
)
)
module Admin::ResourcesHelper
def attributes
resource_class.attribute_names - %w(id created_at updated_at row_order)
end
# resource_class is an inherited_resources helper method
# resource_name(item: resource_class.superclass) # => Menu Item (from a model that inherits from MenuItem)
# resource_name # => Burger
def resource_name(options = {})
options[:item] ||= resource_class
options[:item].name.underscore.humanize.titleize
end
end
class Admin::ResourcesController < Admin::ApplicationController
inherit_resources
respond_to :html
def sort
@menu_item = resource_class.find(params[:id])
@menu_item.attributes = params[:menu_item]
@menu_item.save
render nothing: true
end
protected
def collection
collection_variable_name = controller_name.gsub(/^/, '@').to_sym
instance_variable_set(collection_variable_name, resource_class.rank(:row_order).all)
end
end