How to break records into several models? (do i need a polymorphic compound?)

After quite a lot of searching, I still lost a bit. There are several other similar questions that relate to pagination of several models, but they either do not answer or paganize each model separately.

I need to split all account entries at once.

class Account :has_many :emails :has_many :tasks :has_many :notes end 

So, I would like to find the 30 most recent “things”, regardless of who they are. Is this possible with current pagination solutions?

How to use some combination of impatient download and Kaminari or will_paginate?


Or, should I first create a polymorphic union of all these things called Elements. Then break the pages into the last 30 elements, then browse related records of these elements.

And if so, I'm not quite sure what this code looks like. Any suggestions?


Which way is better? (or even possible)

Rails 3.1, Ruby 1.9.2, the application does not work.

+6
source share
3 answers

with will_paginate:

 @records = #do your work and fetch array of records you want to paginate ( various types ) 

then do the following:

 current_page = params[:page] || 1 per_page = 10 @records = WillPaginate::Collection.create(current_page, per_page, records.size) do |pager| pager.replace(@records) end 

then in your opinion:

 <%=will_paginate @records%> 
+2
source

Good question ... I'm not sure about a “good” solution, but you can make a hack in ruby:

You will need to first extract the last 30 from each type of “thing” and put them in an array indexed by create_at, and then sort this array using create_at and take the top 30.

A completely non-refactored launch might be something like this:

 emails = Account.emails.all(:limit => 30, :order => :created_at) tasks = Account.tasks.all(:limit => 30, :order => :created_at) notes = Account.notes.all(:limit => 30, :order => :created_at) thing_array = (emails + tasks + notes).map {|thing| [thing.created_at, thing] } # sort by the first item of each array (== the date) thing_array_sorted = thing_array.sort_by {|a,b| a[0] <=> b[0] } # then just grab the top thirty things_to_show = thing_array_sorted.slice(0,30) 

Note: not verified, there may be many errors ...;)

+1
source
 emails = account.emails tasks = account.tasks notes = account.notes @records = [emails + tasks + notes].flatten.sort_by(&:updated_at).reverse @records = WillPaginate::Collection.create(params[:page] || 1, 30, @records.size) do |pager| pager.replace(@records) end 

Thats it ... :)

0
source

Source: https://habr.com/ru/post/900455/


All Articles