Ruby/Rails - Limit the size of a object/hash
I have an object called @events containing about 50 records being pulled from a find condition of my model.
I'm currently displaying the results of the @object in my view like this....
<% for event in @events %>
<p><%= @event.name %></p>
<% end %>
Instead of displaying the entire 50 I would like shrin开发者_JAVA百科k the set to about 10 records so it displays better on the page.
I cannot use :limit in the find condition since the object is being composed from a variety of loops where after each iteration it adds a few specific records.
So the issue is I have this object @events with 50 records, how can I change the object after its been composed so only the first 10 records remain?
First of all, if you'd like to have pagination, I strongly suggest taking a look at will_paginate
Alternatively, you can do the following to read the first 10 records only.
<% @events.first(10).each do |event| %>
<p><%= event.name %></p>
<% end %>
Or the last 10 records
<% @events.last(10).each do |event| %>
<p><%= event.name %></p>
<% end %>
I didn't test it but you get the point.
are you looking to completely do away with the other 40 or are you just wanting to pull off 10 per page for display purposes. if you are just doing this for display purposes i would look into the will_paginate gem. through its options you could set it so only 10 results per page are shown.
Take a look at will_paginate
and kaminari
. They both are designed to limit the records retrieved from the database, plus offer helpers for your views to provide the usual number of pages and current page lists.
Will_paginate has been around a while, and is pretty flexible. Kaminari is newer and looks like it has a cleaner interface.
精彩评论