universal_table/app/models/table_entry.rb

56 lines
1.5 KiB
Ruby

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)
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'
self.order_by({field => direction})
else
values = criteria.to_a
field_id = table.table_columns.where(key: field).first || table.table_columns.where(title: field).first
values.each do |v|
v.sort_value = v.column_entries.where(:table_column_id=>field_id).first.sort_value
end
values = values.sort_by{|v| v.sort_value}
if direction=='desc'
values = values.reverse
end
Kaminari.paginate_array(values)
end
end
end