Search code examples
rubyruby-on-rails-3actioncontroller

Retrieve a record's created_by field to a passed in month and year in Rails3?


Im trying to make a side bar for my blog archive that lists out all the months for my blog entries, so when you click on a link such as "June 2007" all the blogs from June 07 are loaded. Heres my link_to

<%= link_to month.first.strftime("%B %Y"), blog_archive_month_path(month.first.strftime("%Y-%m-%d")) %>

month.first is a record I pulled up. Should my controller look something like this?:

@blog_posts = BlogPost.where(:created_at.strftime("%Y-%m-%d") => params[:date]).(:select => "title, id, slug, created_at", :order => "created_at DESC")

I was hoping I could convert the records' created_by field to a format I could pass in an match but I get an undefined method erro


Solution

  • Basically I agree with what Dan Croak is saying (+1). The only mistake in his answer is that .to_date throws an error if there is not a complete date string in params[:date] (like in his example). So my suggestion would be:

    View:

    <%= link_to month.first.strftime("%B %Y"), blog_archive_month_path(month.first.strftime("%Y-%m-%d")) %>
    

    Controller:

    @blog_posts = BlogPost.
      where(:created_at => params[:date].to_date.beginning_of_month..params[:date].to_date.end_of_month).
      order("created_at desc")
    

    The problem with your original code is that you are trying to call strftime on :created_at, which is not possible.

    Or if you don't like a full date in your URL, you could do this:

    <%= link_to month.first.strftime("%B %Y"), blog_archive_month_path(month.first.strftime("%Y-%m")) %>
    

    And:

    @blog_posts = BlogPost.
      where(:created_at => "#{params[:date]}-01".to_date.beginning_of_month.."#{params[:date]}-01".to_date.end_of_month).
      order("created_at desc")