Search code examples
ruby-on-railsransack

ransack sort_link based on a definition method in model


i'm using ransack for my application and trying to create a table head sortable with sort_link, but I'm stuck when i try to applied the sort_link to the table head which contains the value not from the table of the database, but from the method in the model...

this is my code

my model

def final_price_with_items
  self.item_cost + self.final_price
end

and i had a whitelisted in my model to declare the other table head which contains the value from the table of the database.

self.whitelisted_ransackable_attributes = ['number','state', 'cost', 'created_at']

my html

 <table class="index" id="listing_shipments" data-hook>
  <thead>
    <tr data-hook="admin_shipments_index_headers">
      <th><%= sort_link @search, :created_at,  Spree::Shipment.human_attribute_name(:created_at) %></th>
      <th><%= sort_link @search, :number,  Spree::Shipment.human_attribute_name(:number) %></th>
      <th><%= sort_link @search, :state,  Spree::Shipment.human_attribute_name(:state) %></th>
      <th><%= sort_link @search, :cost,  Spree::Shipment.human_attribute_name(:cost) %></th>
      <th><%= sort_link @search, :final_price_with_items,  Spree::Shipment.human_attribute_name(:final_price) %></th>
      <th data-hook="admin_shipments_index_header_actions" class="actions"></th>
    </tr>
  </thead>
  <tbody>
    <% @shipments.each do |shipment|%>
      <tr id="<%= spree_dom_id shipment %>" data-hook="admin_shipments_index_rows" class="<%= cycle('odd', 'even')%>">
        <td><%= l shipment.created_at.to_date %></td>
        <td><%= link_to shipment.number, edit_admin_order_path(shipment.order) %></td>
        <td><span class="state <%= shipment.state.downcase %>"><%= Spree.t("shipment_state.#{shipment.state.downcase}") %></span></td>
        <td><%= shipment.display_cost.to_html %></td>
        <td><%= Spree::Money.new(shipment.final_price_with_items, currency: shipment.currency).to_html %></td>
        <td data-hook="admin_shipments_index_row_actions" class="actions align-center">
          <%= link_to_edit_url edit_admin_order_path(shipment.order), :title => "admin_edit_#{dom_id(shipment)}", :no_text => true %>
        </td>
      </tr>
    <% end %>
  </tbody>
</table>

the table head which declared in whitelisted able to sorting, because the shipment table in database had these column, but the final_price_with_items not work to sorting.. anyone can help me to solve this problem ?


Solution

  • Should be able to do it with a ransacker. I'd maybe change the the name of your sort link to final_price_with_items_sort

    Then in your model add this:

    ransacker :final_price_with_items_sort do Arel.sql('item_cost + final_price') end