對於我的應用程序,我有一個使用ajax檢索記錄的數據表。該數據表允許用戶排序,搜索和我已經添加了一個額外的自定義字段,允許用戶根據類別進行過濾。最好的方式導出ajax/serverside數據表
現在,當我使用datatables提供的HTML5方法導出到CSV/Excel時,我只能得到瀏覽器在導出中顯示的記錄。所以,我唯一的選擇是做一個服務器端導出。我有一個工作的導出功能,但我正在努力找到正確的方式來將我的過濾器傳遞給此導出功能。
我不知道什麼最好的方法是讓我的參數在我的模型中導出方法。我想包括jQuery將參數添加到我的link_to,但我不知道如何做到這一點,如果這被認爲是「良好的做法」。
我的代碼:
表
<%= link_to "Download CSV", vendor_skus_path(format: "csv") %>
<%= select_tag "vendor-select", options_from_collection_for_select(@vendors, "id", "name"), include_blank: true, class:"vendor-select form-control" %>
<table id="vendor-skus-table" class="table table-striped table-bordered table-hover" data-source="<%= vendor_skus_path(format: :json) %>">
<thead>
<tr>
<th>Name</th>
<th>Vendor</th>
<th>Inventory Quantity</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
$('#vendor-select.vendor-select').on('change', function() {
$('#vendor-skus-table').DataTable().ajax.reload();
});
的CoffeeScript
$ ->
$('#vendor-skus-table').DataTable
processing: true
serverSide: true
retrieve: true
pagingType: 'full_numbers'
ajax: data: (d) ->
d.sku = $('#vendor-skus-table').data('source')
d.vendor_id = $('#vendor-select').val();
return
的DataTable
class VendorSkuDatatable < AjaxDatatablesRails::Base
def_delegators :@view, :params, :link_to, :vendor_skus_path, :vendor_path
def sortable_columns
@sortable_columns ||= ['VendorSku.name', 'Vendor.name', 'VendorSku.inventory_quantity' ]
end
def searchable_columns
@searchable_columns ||= ['VendorSku.name', 'Vendor.name']
end
private
def data
records.map do |record|
[
link_to(record.name, record),
link_to(record.vendor.name, record.vendor),
record.inventory_quantity
]
end
end
def get_raw_records
# insert query here
if params[:vendor_id].present?
VendorSku.joins(:vendor).where(vendor_id: params[:vendor_id])
else
VendorSku.joins(:vendor).all
end
end
end
控制器動作
def index
@vendor_skus = VendorSku.order(:name)
@vendor_sku = VendorSku.new
@vendors = Vendor.all
respond_to do |format|
format.html
format.csv { send_data @vendor_skus.to_csv }
format.json { render json: VendorSkuDatatable.new(view_context, { vendor_id: params[:vendor_id] }) }
format.xls # { send_data @vendor_skus.to_csv(col_sep: "\t") }
end
end
模型方法
def self.to_csv(options = {})
CSV.generate(options) do |csv|
csv << column_names
all.each do |product|
csv << product.attributes.values_at(*column_names)
end
end
end
這是一個很好的解決方法。歡呼雀! – stoerebink