Paginate objects from the same loop in Rails

0

I have a slight problem,

I have managed to iterate 2 objects in the same one, my problem is that it does not work with will_paginate , and to be able to do that iteration I support the Ruby method: sort_by but apparently this does not work with any gem of page, what suggestion do you give me, I hope you can give me a hand, here I share my code:

enterprises_controller.rb

def show
  @items = @enterprise.jobs + @enterprise.products
  @items = @items.sort_by do |item| item.created_at end
  @items = @items.reverse
end

show.html.erb

<% @items = @items.each do |item| %>
  <%= item.name %> <br>
<% end %>
    
asked by Hector Hernandez 20.01.2017 в 20:32
source

2 answers

2

In this case, you should use the sort method for an array which has the following structure and allows you to sort any arrangement for any of the attributes of its objects.

my_array.sort! { |a, b|  a.attribute <=> b.attribute }

In this case, the result would be very similar to:

my_array = @items.sort! { |a, b|  a.created_at <=> b.created_at }

For paging you need to use in addition to will_paginate your module for fixes, with require 'will_paginate/array'

Which is used as follows:

my_array.paginate(:page => params[:page], :per_page => 30)
    
answered by 20.01.2017 / 21:03
source
1

Here the process:

Inside a file in config / initializers , it can be " will_paginate.rb ", add: require 'will_paginate/array'

And the controller stayed like this:

def show
    @items = @enterprise.jobs + @enterprise.products
    @items = @items.sort! { |a, b|  a.created_at <=> b.created_at }
    @items = @items.reverse.paginate(:page => params[:page], :per_page => 4)
end

and the show view:

<%= will_paginate @items, :container => false %>
    
answered by 20.01.2017 в 21:43