I have a rails 4 application that has the sunspot gem and uses json to respond to the datatables jquery plugin. I'm loosely following this railscast: http://railscasts.com/episodes/340-datatables
My index in my controller looks like this now:
def index
@search = Product.search do |query|
query.fulltext params[:sSearch]
query.with(:store_id, @collection.id)
query.paginate(:page => params[:page] || 1, :per_page => 35)
end
@products = @search.results
@headers = @products.map(&:data).flat_map(&:keys).uniq
@product_data = @products.map{ |product| product[ :data ].values }
respond_to do |format|
format.html
format.json do
render :json=> {
"sEcho" => params[:sEcho].to_i,
"iTotalRecords" => @products.count,
"iTotalDisplayRecords"=> @products.count,
"aaData" => @product_data.as_json
}
end
end
end
Now I'm trying to get the ordering and paging working with the search block I have, but I can't figure out how to do it. So basically I'm trying to take this code:
def fetch_products
products = Product.order("#{sort_column} #{sort_direction}")
products = products.page(page).per_page(per_page)
end
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 = %w[name category released_on price]
columns[params[:iSortCol_0].to_i]
end
def sort_direction
params[:sSortDir_0] == "desc" ? "desc" : "asc"
end
and merge it with what I already have.
Thanks for all help!
It looks like you are trying to do everything in your controller and very little reference to your datatable.
If you want to search using sunspot then in the datatable, change the following lines
def fetch_products
products = Product.order("#{sort_column} #{sort_direction}")
products = products.page(page).per_page(per_page)
if params[:sSearch].present?
@search = Product.search do |query|
query.fulltext params[:sSearch]
query.with(:store_id, @collection.id)
query.paginate(:page => params[:page] || 1, :per_page => 35)
end
products = @search.results
end
products
end
In your controller,
def index
respond_to do |format|
format.html
format.json { render json: ProductsDatatable.new(view_context) }
end
end
Keep other codes in datatable
as it is.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.