In my rails app, I am using jquery-datatables-rails
. It works fine for single model. But if I have associated model then I don't know how to use sort_column function. My code is below0.
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
My product.rb
class Product < ActiveRecord::Base
delegate :email, to: :owner, allow_nil: true, prefix: true
belongs_to :owner, :class_name => "Owner"
as you can see, in sort_column
method I am using owner.email
since in data
method I have product.owner.email
. But this does not sort the table. I think this is not the correct way to use it. Here product and owner are two different model with has_many relationship. Please let me know how can I make it work.