Search code examples
mysqlruby-on-railsrubygemssmart-listing

How can I use an instance method instead of a MySQL field with SmartListing gem?


I'm using the SmartListing gem with my Ruby (2.1.2p95) on Rails (4.0.0) project to create a sortable/paginating table from an ActiveRecord group of records, let's call them Orders. Each Order can have many Items, each of which has a Cost field on their table. I need to be able to sort by Order Number (field in Order table), number of Items (class method on Order model), and total cost (class method on Order model).

Is there a way, using explicit sort_attributes, to call the method (i.e. order.item_total or order.number_of_items) instead of using a field in the MySQL table, which doesn't exist? There are no 'item_totals' columns or 'number_of_items' columns in the 'orders' table, both of those calls are an aggregate of fields/counts in the 'items' table.

@orders = smart_listing_create(:orders, @user.orders, partial: 'orders/order', sort_attributes: [[:id, 'id'],[:item_total, '???'],[:number_of_items, '???']]

Thanks in advance for any help and let me know if I can clarify anything as well.

-Dave


Solution

  • So there isn't any way to do exactly what I'm asking the way I'm asking for it to be done (basically combining Ruby code with SQL). However, there is still a solution! Since smart_listing does support explicit sorting (sorting by joined column names, i.e. [:created_at, 'orders.items.created_at'] if orders.joins(:items)), you can simply create some derived tables and sort them using explicit sorting. Voila!