rmagnum2002
rmagnum2002

Reputation: 11421

filter records by year

Need to filter Articles by year using created_at field.

I got the links for years in articles like this:

Article helper:

  def artcles_by_years
    Article.uniq.pluck("EXTRACT(YEAR FROM created_at)")
  end

index.html.erb

  <% for art in artcles_by_years do %>
    <%= link_to art %>
  <% end %>

it displays: 2009 2010 2011 2012, sure, non-working links.

Question:

How would I build working links and query in controller to filter Articles by year, like pressing 2009 and return all articles created in 2009. Thank you.

Upvotes: 1

Views: 1163

Answers (1)

siddick
siddick

Reputation: 1478

You can add a scope to your model

scope :year, lambda{|year|
  where(" EXTRACT(YEAR FROM created_at) = ? ", year ) if year.present?  
}

And use the scope in your controller:

@articles = Article.year(params[:year])

Display link as:

<%= link_to art, articles_path( :year => atr) %>

Upvotes: 6

Related Questions