2

在我的 Rails 应用程序中,我使用的是jquery-datatables-rails. 它适用于单个模型。但是如果我有关联的模型,那么我不知道如何使用 sort_column 函数。我的代码低于0。

delegate :params, :h, :link_to, :image_tag, :edit_product_path, to: :@view

  def initialize(view)
    @view = view
  end

  def as_json(options = {})
    {
        sEcho: params[:sEcho].to_i,
        iTotalRecords: Product.count,
        iTotalDisplayRecords: products.total_entries,
        aaData: data
    }
  end

  private

  def data
[
          product.name,
          product.number,
          product.owner_email
      ]
  end

def products
    @products||= fetch_products
  end

  def fetch_products
    products= Product.order("#{sort_column} #{sort_direction}")
    products= products.page(page).per_page(per_page)
    if params[:sSearch].present?
      products= products.where("namelike :search", search: "%#{params[:sSearch]}%")
    end
    products
  end

  def page
    params[:iDisplayStart].to_i/per_page + 1
  end

  def per_page
    params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10
  end

  def sort_column
    columns = %w[name number owner_email]
    columns[params[:iSortCol_0].to_i]
  end

  def sort_direction
    params[:sSortDir_0] == "desc" ? "desc" : "asc"
  end

我的产品.rb

class Product < ActiveRecord::Base
  delegate :email, to: :owner, allow_nil: true, prefix: true
  belongs_to :owner, :class_name => "Owner"

如您所见,在sort_column我使用的方法中,owner.email因为在data方法中我有product.owner.email. 但这不会对表格进行排序。我认为这不是正确的使用方法。这里产品和所有者是具有 has_many 关系的两个不同模型。请让我知道如何使它工作。

4

1 回答 1

1
products= Product.order("#{sort_column} #{sort_direction}")

This is where the sorting happens. If the sort_column is owner.email then you need owners table to be preloaded alongside with the products table. So you need this joins:

products= Product.joins(:owner).order("#{sort_column} #{sort_direction}")

and plural name in sort_columns:

columns = %w[name number owners.email]

But we don't need to load owners table when sorting is done for name and number columns. To solve this problem it's better to define a method that returns relation name by search column name:

def joins_relation(column)
  case column
  when 'owners.email'
    :owner
  else
    nil
  end
end

And use it like this:

products= Product.joins(joins_relation(sort_column)).order("#{sort_column} #{sort_direction}")
于 2015-12-28T14:06:08.553 回答