私のアプリケーションでは、レコードを取得するためにajaxを使用するデータテーブルがあります。データテーブルを使用すると、ユーザーは並べ替え、検索が可能になり、ユーザーがカテゴリに基づいてフィルタリングできる余分なカスタムフィールドが追加されました。ajax/serversideデータテーブルをエクスポートする最良の方法
データテーブルで提供されるHTML5メソッドを使用してCSV/Excelにエクスポートすると、ブラウザでエクスポートされたレコードのみが取得されます。だから、私の唯一の選択肢は、サーバー側のエクスポートを行うことです。私は実際のエクスポート関数を持っていますが、このエクスポート関数にフィルタを渡す適切な方法を見つけるのには苦労しています。
私のモデルのエクスポートメソッドにパラメータを設定するのが最も良い方法はわかりません。私はlink_toにパラメータを追加するためにjQueryをインクルードすることを考えましたが、これをどうやって行うのか、そしてこれが「良い方法」と考えられるのかどうかはわかりません。
マイコード:
表
<%= 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