【问题标题】:How to sort jquery datatables column for associated records in rails如何对rails中关联记录的jquery数据表列进行排序
【发布时间】:2016-04-02 08:48:13
【问题描述】:

在我的 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 关系的两个不同模型。请让我知道如何使它工作。

【问题讨论】:

    标签: jquery ruby-on-rails datatables jquery-datatables-rails


    【解决方案1】:
    products= Product.order("#{sort_column} #{sort_direction}")
    

    这是排序发生的地方。如果sort_columnowner.email,那么您需要将owners 表与products 表一起预加载。所以你需要这个joins:

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

    sort_columns中的复数名称:

    columns = %w[name number owners.email]
    

    但是当对名称和数字列进行排序时,我们不需要加载owners 表。为了解决这个问题,最好定义一个通过搜索列名称返回关系名称的方法:

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

    并像这样使用它:

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

    【讨论】:

    • 您是否将此代码添加到产品模型中?您是否将data 中的product.owner.email 更改为product.owner_email
    • 对不起!我必须在我的产品模型中添加什么?我没有在产品模型中添加任何东西
    • 我的回答中的一行代码。它允许您调用product.owner_email 而不是product.owner.email。您还需要在数据表初始化期间正确指定列名,以便iSortCol_0 参数包含owner_email 对应列的值。
    • 请查看我更新的问题以及您给定的更改。但还是不行
    • 好吧,对不起,我的回答错了。我没有太注意代码。还原更改并查看更新的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多