I have two models (Folder and Document) which I need to show in a single view together. However, to reduce the number of queries sent I am collecting the Documents only if the folders are less than 12 (my :per_page
). While this is working fine, I am stuck in a particular case,
When my total documents are less than 12 and folders are less than 12 but together are more than 12, the pagination fails.
Below is the code to calculate which page to be shown where f_page
returns the page for the Folder pagination and d_page
returns the page number for the document collection.
def f_page(page_cnt, size)
page_cnt.present? and size.nonzero? ? page_cnt.to_i <= (size/12 + (size%12==0 ? 0 : 1)) ? page_cnt.to_i : (size / 12 ) + (size%12==0 ? 0 : 1) : 1
end
def d_page(page_cnt, fc, dc)
page_cnt = page_cnt.present? ? page_cnt : 1
puts page_cnt
dpg = 1
if (fc/12+1 == page_cnt.to_i)
dpg = 1
elsif ((fc/12+1) < page_cnt.to_i)
if (fc < 12)
unless (dc <= 12)
dpg = page_cnt
else
dpg = 1
end
else
(fc/12 == 0) ? (dpg = page_cnt.to_i - (fc/12+1)) : (dpg = page_cnt.to_i - (fc/12))
end
end
puts "dpg = #{dpg}"
return dpg
end
Both are together collected and paginated which is shown in the view.
f = Folder.action_folder_collection(@action, current_user).paginate(:page => params[:page], :per_page => 12)
if (f.count < 12)
d = Document.action_document_collection(@action, current_user).paginate(:page => d_page(params[:page], total_folders, total_documents), :per_page => per_page-f.count)
end
collection << f
collection << d
@collection = collection.flatten.paginate(:page => 1,:per_page => 12,:total_entries => total)
How do I solve it?