Reputation: 4089
I am building a simple blog app and I want to add an archive were people can click on a month and all articles in that month are displayed. It's like grouping based on the month and year. For example,
Articles:
So when clicking on a date it takes you to a page and lists all the articles of that month. How can I get it done?
Upvotes: 0
Views: 77
Reputation: 6476
For July 2012:
require 'date'
month = 7
year = 2012
start_date = Date.new(year,month,1)
end_date = Date.new(year,month+1,1) - 1.day
articles_in_july = Article.where(:created_at => start_date..end_date)
You can test in a console with the above. However, in your model you probably want:
def self.in_month(month,year)
start_date = Date.new(year,month,1)
end_date = Date.new(year,month+1,1) - 1.day
where(:created_at => start_date..end_date)
end
Then you can call:
Article.in_month(7,2012)
or, assuming a User has_many articles:
current_user.articles.in_month(7,2012)
Upvotes: 1