Сортировочные ассоциации Ransack - PullRequest
0 голосов
/ 06 апреля 2020

Я немного новичок в Rails в целом, и в настоящее время я пытаюсь заставить сортируемые столбцы работать с помощью Ransack. Я сталкиваюсь с проблемой сортировки связанных столбцов. Ниже приведен пример моего кода, в котором таблица Product пытается отсортировать имена поставщиков.

Я попытался заменить: имя_поставщика на «имя.поставщика.supplier_», как предложил README, но безрезультатно.

Контроллер

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>

1 Ответ

0 голосов
/ 06 апреля 2020

Разобрался. Я должен назвать это ассоциативным именем. Так что в этом случае это будет

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