Rails 3.2 friendly url routing by date

后端 未结 2 414
执念已碎
执念已碎 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: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.

提交回复
热议问题