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

      

+3


source to share


3 answers


Alternative to existing answers if only an array of years is needed:

@years = Article.uniq.pluck("EXTRACT(YEAR FROM created_at)")

      



which generates the following SQL query:

SELECT DISTINCT EXTRACT(YEAR FROM created_at) FROM `articles`

      

+3


source


@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

      

+1


source


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.

0


source







All Articles