I'd like to set the upper limit for display of the Rails each statement.

Asked 1 years ago, Updated 1 years ago, 486 views

What do you want to do
In my own application, I use the following each statement to display posts, but I would like to limit the display limit to 10.
At that time, I would like to make the specification disappear from the old one.

<%@notifications.each do | notification|%>
  <div class="notifications-index-item">
  <%case notification.action%>
  <%when "post"%>
    <%=link_to(notification.post.dear, "/posts/#{notification.post.id}")%>br>
  <%when "reply"%>
    <%=link_to(notification.reply.dear, "/replies/#{notification.reply.id}")%>br>
  <%else%>
    <p> Not yet here</p>
  <%end%>
  </div>
<%end%>

If things go on as they are now, the posts will probably be displayed indefinitely, so please let me know.

ruby-on-rails ruby

2022-11-04 00:00

1 Answers

@notifications depends on the nanny:

  • For arrays
    @notifications.sort_by.reverse.take(10).each do...
    I think it would be good to rearrange it as shown in and then use Array#take.
    You can sort by sort_by{...}.reverse instead of sort{|a,b|b.date and time items <=>a.date and time items}.
    If the order of arrangement is already new, I think you just need to add take.
  • For AcitveRecord model query results
    You can add order (date and time attribute you want to sort::desc).limit(10) to the query.
    If you have already placed an order, I think you just need to add a limit.


2022-11-04 00:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.