class TableEntry include Mongoid::Document include Mongoid::Timestamps include Slug attr_accessor :sort_value field :sort_number, type: Integer, default: 0 has_many :column_entries, :dependent => :destroy belongs_to :u_table accepts_nested_attributes_for :column_entries, :allow_destroy => true def self.u_table UTable.find(criteria.selector['u_table_id']) end def self.sorting(params: nil,table: nil,field: nil,direction: nil,page_num: nil,per: nil,column_entries: nil,paginated: true) page_num = 1 if page_num.blank? page_num = page_num.to_i if table.nil? table = u_table end if field.nil? || direction.nil? if !params[:sortcolumn].blank? field = params[:sortcolumn] direction = params[:sort] else field = params[:sort].blank? ? nil : params[:sort] direction = params[:order].blank? ? 'desc' : params[:order] end if field.nil? field = table.default_ordered_field if field != 'created_at' columns = table.table_columns sort_column = columns.where(:key=>field).first || columns.where(:title=>field).first direction = sort_column.order_direction end end end field = field.to_s if (field=='created_at' || field == 'sort_number') && column_entries.nil? values = self.order_by({field => direction}) if !per.nil? values = values.page(page_num).per(per) end else column_to_sort = table.table_columns.where(key: field).first || table.table_columns.where(title: field).first if column_entries.nil? if criteria.selector.keys != ['u_table_id'] column_entries = ColumnEntry.where(:table_column_id=>column_to_sort.id,:table_entry_id.in => criteria.pluck(:id)).order_by(column_to_sort.sort_hash(direction)) else column_entries = ColumnEntry.where(:table_column_id=>column_to_sort.id).order_by(column_to_sort.sort_hash(direction)) end else column_entries = ColumnEntry.where(:table_column_id=>column_to_sort.id,:table_entry_id.in => (column_entries.class==Kaminari::PaginatableArray ? column_entries.map(&:table_entry_id) : column_entries.pluck(:table_entry_id))).order_by(column_to_sort.sort_hash(direction)) end if !per.nil? total_count = column_entries.count column_entries = column_entries.page(page_num).per(per) offset = page_num==0 ? 0 : (page_num-1)*per end_offset = (total_count-offset-per) end_offset = 0 if end_offset<0 values = Kaminari.paginate_array([nil]*offset+column_entries.map{|v| v.table_entry}+[nil]*end_offset).page(page_num).per(per) else values = column_entries.map{|v| v.table_entry} if paginated values = Kaminari.paginate_array(values) end end end values end end