Skip to content

Instantly share code, notes, and snippets.

@hexgnu
Created January 10, 2012 05:13
Show Gist options
  • Save hexgnu/1587132 to your computer and use it in GitHub Desktop.
Save hexgnu/1587132 to your computer and use it in GitHub Desktop.
Method
# Scope to order by a column header in a view's table.
# Direction can also be passed as argument (defaults to 'DESC').
# NOTE: Do not use #includes, instead use #joins. See not at CSVExporter.
def self.ordered_by_viewable_column(view_column_name, direction = 'DESC')
# Direction must be either asc or desc. Default to DESC
dir = direction =~ %r{^(asc|desc)$}i ? direction.upcase : 'DESC'
case view_column_name
when /account/i then joins(:network).order("networks.name #{dir}")
when /author/i then joins(:author).order("users.last_name #{dir}, users.first_name #{dir}")
when /brand/i then joins(:brand).order("brands.name #{dir}")
when /id/i then order("posts.id #{dir}")
when /message/i then order("LOWER(message) #{dir}")
when /platform/i then joins(:network).order("networks.type #{dir}")
when /scheduled/i then order("scheduled_at #{dir}")
when /status/i then order("moderated_status #{dir}")
when /time/i then order("created_at #{dir}")
else ordered_by_viewable_column('Scheduled', 'ASC')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment