Rails:在视图中按月份显示记录,还有其他方式吗?

发布于 2024-11-05 20:16:33 字数 659 浏览 2 评论 0原文

场景: 我有一堆火柴。我想在我的视图中创建一个带有 HTML 链接的侧栏,您可以在其中按月查看匹配项。这是我当前的实现:

当前解决方案

#Controller
@matches_by_month = Match.find(:all).group_by {|match| match.kickoff.strftime('%B %Y')}

#View
<%  @matches_by_month.each do | month, matches | %>
<%=link_to month %><br>
<% end %>

# Returns in the side column links that look like this.
# April 2011
# May 2011
# Which is great!

寻求建议: 我认为这不是一个好的解决方案,因为经过一段时间该页面的速度会变慢。正确的?到 2013 年,我可能拥有 1500 条记录,为了获取月份而连续查找(:所有)匹配项似乎是一种浪费。我可以使用其他解决方案吗?我是否应该在“匹配”之外保留一个单独的表来跟踪月份。也许我想太多了,目前的解决方案还可以。想法?

SCENARIO:
I have bunch of matches. I want to create in my view a side column with HTML links where you can view the matches by month. Here is my current implementation:

CURRENT SOLUTION:

#Controller
@matches_by_month = Match.find(:all).group_by {|match| match.kickoff.strftime('%B %Y')}

#View
<%  @matches_by_month.each do | month, matches | %>
<%=link_to month %><br>
<% end %>

# Returns in the side column links that look like this.
# April 2011
# May 2011
# Which is great!

SEEKING ADVICE:
I'm thinking that this is not a good solution because over a period of time this page will slow down. Right? By 2013 I could have 1500 records and it seems like a waste to continuously find(:all) matches in order to get the months. Is there another solution I can use? Should I keep a separate table outside of 'matches' that tracks the months. Maybe I'm overhtinking this and the current solution is ok. Thoughts?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

喜爱皱眉﹌ 2024-11-12 20:16:33

如果可以安全地假设第一条记录和最后一条记录之间每个月都有匹配项,您可以:

# for your sidebar
start_date = Match.first.kickoff.to_date
end_date = Match.last.kickoff.to_date

<% start_date.step(end_date, 1.month) do |date| %>
  <%= link_to date.strftime('%%B %Y'), matches_by_month_path(date) %>
<% end %>

然后在控制器中只需解析所选日期并使用 Match.where(...) 进行条件查找

If it is safe to assume that there are matches every month between the first record and the last record you can:

# for your sidebar
start_date = Match.first.kickoff.to_date
end_date = Match.last.kickoff.to_date

<% start_date.step(end_date, 1.month) do |date| %>
  <%= link_to date.strftime('%%B %Y'), matches_by_month_path(date) %>
<% end %>

And then in your controller just parse the date selected and do a conditional find using Match.where(...).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文