Rails 3.2 friendly url routing by date

后端 未结 2 395
执念已碎
执念已碎 2021-01-01 03:06

I want to implement blog\\news application with ability to:

  1. show all posts at root: example.com/
  2. show all posts answering some year:
相关标签:
2条回答
  • 2021-01-01 03:53

    Is this your full routes.rb file? Sounds like you might have a preceding resources :posts entry, which basically matches /posts/:id. Also, there's nothing I can see from the routes file you posted that could be causing a redirect from the root path to posts, so it must be something else in there.

    0 讨论(0)
  • 2021-01-01 03:57

    The problem was in post's path helper usage as post_path(post), because first parameter must be year since I use :as => :post in parametrized match in routes.rb.

    Nevertheless, to make the entire solution clear here are some actions needed to make that all work proper:

    1. You must add proper path helpers names for each match, e.g.

      # Get /posts/2012/07/slug-of-the-post
      match "/posts/:year/:month/:slug", <...>,
        :as => :post_date
      

      Now you can use post_date_path("2012","12","end-of-the-world-is-near") in views.

      Same for posts_path, posts_year_path("2012"), posts_month_path("2012","12") if properly named.

      I advice not to use neither :as => :post in that match nor creating to_param in model file as it can break something you don't expect (as active_admin for me).

    2. Controller file posts-controller.rb should be filled with posts that needed extraction and checking of date's correctness before slug. Nevertheless in this state it is OK and breaks nothing.

    3. Model file posts.rb should be filled with year and month extraciton in proper format, e.g.:

      def year
        created_at.year
      end
      
      def month
        created_at.strftime("%m")
      end
      

      There is no to_param method really needed as I've noticed already.

    0 讨论(0)
提交回复
热议问题