Skip to content

Instantly share code, notes, and snippets.

@jackii
Created September 6, 2012 13:55
Show Gist options
  • Save jackii/3656496 to your computer and use it in GitHub Desktop.
Save jackii/3656496 to your computer and use it in GitHub Desktop.
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protected
# for datatables
def page
params[:iDisplayStart].to_i/per_page + 1
end
def per_page
params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10
end
def sort_column
columns ||= []
columns[params[:iSortCol_0].to_i]
end
def sort_direction
params[:sSortDir_0] == "desc" ? "desc" : "asc"
end
end
# config/csv_renderer.rb
ActionController::Renderers.add :csv do |obj, options|
filename = options[:filename] || 'data'
str = obj.respond_to?(:to_csv) ? obj.to_csv : obj.to_s
send_data str, :type => Mime::CSV,
:disposition => "attachment; filename=#{filename}.csv"
end
# app/views/posts/index.json.jbuilder
json.sEcho params[:sEcho].to_i
json.iTotalRecords Post.count
json.iTotalDisplayRecords @posts.total_count
posts = Array.new
@posts.each do |post|
posts << [
link_to(post.id, edit_post_path(post)),
post.title,
post.subtitle,
post.descriptions,
post.author
(post.publish_date.strftime("%d-%m-%Y") unless post.publish_date.blank?),
]
end
json.aaData posts
# app/models/post.rb
class Post < ActiveRecord::Base
# other codes ...
def self.to_csv(posts, options={})
if posts.first.class.superclass == ActiveRecord::Base
which_columns = export_columns
CSV.generate do |csv|
csv << which_columns
posts.each do |row|
csv << which_columns.collect{ |attribute| row[attribute] }
end
end
else
CSV.generate_line(posts, Hash.new)
end
end
def self.export_columns
columns ||= %w[id title subtitle author descriptions]
end
end
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
def index
@posts = Post.order("#{sort_column} #{sort_direction}").page(page).per(per_page)
if params[:sSearch].present?
sql = "
title like :search
or subtitle like :search
or descriptions like :search
or author like :search"
@posts = @posts.where(sql, search: "%#{params[:sSearch]}%")
end
respond_to do |format|
format.json
format.html
format.csv { render :csv => Post.to_csv(@posts, columns:params[:aoColumns])}
end
end
protected
def sort_column
@columns ||= Post.export_columns
# or
# @columns || = [id title subtitle descriptions author]
@columns[params[:iSortCol_0].to_i]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment