搜索 sort_link 基于模型中的定义方法

ransack sort_link based on a definition method in model

我正在为我的应用程序使用搜索并尝试使用 sort_link 创建一个 table head sortable,但是当我尝试应用 sort_link 到 table 头,其中包含的值不是来自数据库的 table,而是来自模型中的方法...

这是我的代码

我的模型

def final_price_with_items
  self.item_cost + self.final_price
end

并且我在我的模型中有一个白名单来声明另一个 table 头,其中包含来自数据库 table 的值。

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

我的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>

在白名单中声明的​​table头能够排序,因为数据库中的发货table有这些列,但是final_price_with_items无法排序..任何人都可以帮忙我来解决这个问题?

用掠夺者应该可以做到。我可能会把你的名字 link 改成 final_price_with_items_sort

然后在您的模型中添加:

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