首页 > 解决方案 > Ransack 分拣协会

问题描述

一般来说,我对 Rails 有点陌生,目前我正在尝试使用 ransack 让可排序的列工作。我遇到的一个问题是让关联的列进行排序。下面是我的代码示例,其中 Product 表正在尝试对供应商名称进行排序。

我尝试按照自述文件的建议将 :supplier_name 替换为 'suppliers.supplier_name',但无济于事。

控制器

def index
    @search = Product.search(params[:q])
    @products = @search.result.includes(:supplier)
end

模型

class Product < ApplicationRecord
  belongs_to :supplier
end
class Supplier < ApplicationRecord
  has_many :products, inverse_of: :supplier, dependent: :destroy
end


产品索引

<table>
  <thead>
    <tr>
      <th><%= sort_link @search, :product_name, "Name" %></th>
      <th><%= sort_link @search, :product_description, "Description" %></th>
      <th><%= sort_link @search, :product_cost, "Cost" %></th>
      <th><%= sort_link @search, :product_category, "Category" %></th>
      <th><%= sort_link @search, :product_status, "Status" %></th>
      <th><%= sort_link @search, :date_modified, "Date Modified" %></th>
      <th><%= sort_link @search, :supplier_name, "Supplier" %></th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @products.each do |product| %>
      <tr>
        <td><%= sanitize product.product_name.html_safe %></td>
        <td><%= sanitize product.product_description.html_safe %></td>
        <td><%= sanitize number_to_currency(product.product_cost).html_safe %></td>
        <td><%= sanitize product.prodcategory.category.html_safe %></td>
        <td><%= sanitize product.prodstatus.status.html_safe %></td>
        <td><%= sanitize product.date_modified.strftime("%B %-d, %Y").html_safe %></td>
        <td><%= sanitize product.supplier.supplier_name.html_safe %></td>
        <td><%= link_to 'Details', product %></td>
        <td><%= link_to 'Edit', edit_product_path(product) %></td>
        <td><%= link_to 'Delete', product, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

标签: ruby-on-railssortingransack

解决方案


弄清楚了。我必须用 Association_fieldname 来命名它。所以在这种情况下,它将是

 <th><%= sort_link @search, :supplier_supplier_name, "Supplier" %></th>

推荐阅读