Ruby: how to get all available years in rails 3 model
I have many articles in my rails 3 app. To put the index page links how can I get all available years (from created_at attribute) in an array to do something like this
years.do | year |
= link_to year, articles_path(:year => year)
any ideas how to do this with minimal effort (in regards to DB queries)?
Hi Adrian
EDIT1: This may not be the best / fastest. But fl00r reminded me of the collection:
@years = []
Article.pluck(:created_at).each do | year |
@years << year.strftime("%Y")
end
@years = @years.uniq.reverse
source to share
@years = Article.select("YEAR(created_at) as year").group("YEAR(created_at)").pluck(:year)
@years.each do |year|
= link_to year, articles_path(year: year)
end
or as @seph pointed out
@years = Article.select("DISTINCT YEAR(created_at) as year").pluck(:year)
@years.each do |year|
= link_to year, articles_path(year: year)
end
source to share
This solution depends a lot on your database, but it should be fast.
Create a class method to select articles by date in their timestamp created_at
. Here's a SQLite example:
class Article
def self.by_year(year)
where(['strftime("%Y", created_at) = "?"', year])
end
end
Then your controller can call this method like this:
@articles = Article.by_year(params[:year])
There is a small syntax error in your view code (there years.do
should be years.each do
), but other than that it looks ok.
source to share