Reputation: 5197
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>
Upvotes: 4
Views: 3515
Reputation: 2714
Use 8.3 reorder
The reorder method overrides the default scope order. For example:
@categories = Category.includes(:subcategories).where(active: true).references(:subcategories).order(name: :asc).reorder('categories.name ASC', 'subcategories.name ASC')
http://guides.rubyonrails.org/active_record_querying.html
Upvotes: 0
Reputation: 35531
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.
Upvotes: 2
Reputation: 61437
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.
Upvotes: 8