Created
August 11, 2014 09:00
-
-
Save vladimir-e/e1e5288fbaefd5df48aa to your computer and use it in GitHub Desktop.
Orderable concern rails 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Admin::SizesController < Admin::AdminController | |
include OrderableController | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Size < ActiveRecord::Base | |
include Orderable | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Orderable | |
extend ActiveSupport::Concern | |
included do | |
default_scope { order("`order` ASC") } | |
after_initialize :max_order!, :if => Proc.new {|row| row.order == 0} | |
end | |
module ClassMethods | |
def sort(ids) | |
order = 1 | |
ids.each do |id| | |
update id, :order => order | |
order += 1 | |
end | |
end | |
end | |
private | |
def max_order! | |
self.order = self.class.name.constantize.maximum(:order).to_i + 1 | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module OrderableController | |
def sort | |
model = self.class.name.split("::").last.gsub(/Controller/, '').singularize | |
var_name = model.underscore | |
sequence = params[:order].gsub(/#{var_name}\[\]=/, '').split("&") | |
model.constantize.sort sequence | |
render nothing: true | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment