开发者

Rails : Show records by months in the view, any other way?

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,开发者_Go百科 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?


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(...).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜