jbox-web/ajax-datatables-rails

has_scope gem support

emilenriquez opened this issue · 15 comments

https://github.com/plataformatec/has_scope

this gem simplifies the need to create long hard coded queries that makes the function bloated.
is there any chance we can use this to query the data?

format.json { render json: InvoiceDatatable.new(view_context, { current_org: current_organization }) }
class Foo < AjaxDatatablesRails::Base
  include HasScope

  has_scope :featured, :type => :boolean
  has_scope :by_degree
  has_scope :by_period, :using => [:started_at, :ended_at], :type => :hash

  def get_raw_records
    apply_scopes(current_organization.invoices).all
  end

  private

  def current_organization
    options[:current_org]
  end
end

Don't use :only or :except options or it will crash with Unknow method :action_name

what I did was I passed in the query to the the a datatable

format.json { render json: InvoiceDatatable.new(view_context, {current_org: current_organization, query: apply_scopes(current_organization.invoices.order(created_at: :desc)).all}) }

and in the datatable file


  def get_raw_records    
    options[:query]
  end

It sounds like an anti pattern. Does the solution I propose work? (I didn't try it, just read the code of has_scope)

ohh I see. will try your code above

I'm guessing it will loop through the columns and wouldn't be able to read the params defined in the has_scope?

NoMethodError in InvoicesController#index

undefined method `to_unsafe_h' for nil:NilClass
Extracted source (around line #74):

I've updated the example above

this worked like a charm!

and neat code!!

Ok. I will take a look when I can.

@emilenriquez does it work?

it did work @n-rodriguez thanks!

Hi @emilenriquez, I would like to use has_scope with ajax call, so I don't need to reload my page, do you have any idea how can do it?

For example, I would add a checkbox for show/hide inactive users (it is a boolean in the table), if user check or uncheck the checkbox I would like to trigger the call and refresh my table and also when a user clicks in sort arrows in a specific column this value for inactive users can be included in the ajax call.

Thanks for any help here.

@emilenriquez it looks it should be a good option for including my custom params into the ajax call, but i do not find how to trigger the datatable ajax call when the user clicks the show the inactive users

https://datatables.net/examples/server_side/custom_vars.html

@cesar82 Have you been able to figure out how to refresh your DataTable without a page reload?

@andreibondarev yes!

This method DataTable().ajax.reload() reloads the table and take the user to page 1, if you want to keep the current page use this way DataTable().ajax.reload(null, false)

Thanks