Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I limit the number of records to load in view???

This code shows all the records of CommunityTopic that belongs to current Community. How can I limit the numbers to 10 records to display here?

<ul>
  <% @community.community_topics.each do |topic| %>
    <li>
    <%= link_to topic.title, community_topic_path(@community, topic) %>
    <%= link_to topic.user.user_profile.nickname, community_topic_path(@community, topic) %>
    </li>
  <% end %>
</ul>
like image 798
HUSTEN Avatar asked Dec 26 '22 12:12

HUSTEN


2 Answers

Use the limit method:

<% @community.community_topics.limit(10).each do |topic| %>

This will only supply the first 10 elements of the collection to the block. If you want to be more sophisticated, you could use something like will_paginate.

In general, such data fetching should take place in the controller. So instead of having a @community variable where the view gets the data from, have a @community_topics as well, which is prefilled with the data you want to render.

like image 198
Femaref Avatar answered Jan 15 '23 01:01

Femaref


You shouldn't usually do this in the view, but rather in the controller. You can use limit as @Fermaref proposed, or you can use a paginator to help you out such as will_paginate or kaminari.

To move this to the controller, try something like this:

def some_action
  @community = Community.find(params[:id])
  @community_topics = @community.community_topics.order(:some_attribute).limit(10)
end

Then just use @community_topics in your view. One advantage here is that you can now move this logic to a private method for reuse if needed. You can also functionally test that @community_topics limits to 10 rows.

like image 26
PinnyM Avatar answered Jan 15 '23 00:01

PinnyM