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>
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With