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