简体   繁体   中英

Rails Post Date Params

I am attempting to build a Rails blog and I am currently in the final stages. I've managed to work around and develop most if not all features of a Wordpress blog, but one which is currently blocking me is being able to have an 'archive' of blogs. I know how to display a post by it's date time and/or sort posts which were created at a specific time, but i'm unsure how to have a page with a month and year and display those posts.

For example I've uploaded a post in July 2014, how could I automatically have rails create a new page with parameters called /july-2014 which would then automatically display Posts where created_at == july 2014 .

The creation of a new parameter with a set field is my main problem.

Thanks

You need a catch-all route for routes like /july-2014 to work, so put this at the bottom of your routes file:

get '/:month_name', to: 'posts#index'

The string July-2014 should actually be parseable as is, so give this a try:

Class PostController < ApplicationController
  def index
    date = Date.parse(params[:month_name])
    @posts = Post.where("created_at >= ? AND created_at <= ?", date.beginning_of_month, date.end_of_month)
  end
end

This example is the bare minimum, you'll probably want to guard against invalid dates and missing month_name param

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM