Rails 3.2 Friendly Date Routing

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

  • show all messages from root: example.com/
  • show all messages responding for one year: example.com/2012/
  • show all posts for the year and month: example.com/2012/07/
  • show message by its date and bullet: example.com/2012/07/slug-of-the-post

So, I created a layout for the file routes.rb:

# GET /?page=1
root :to => "posts#index"

match "/posts" => redirect("/")
match "/posts/" => redirect("/")

# Get /posts/2012/?page=1
match "/posts/:year", :to => "posts#index",
  :constraints => { :year => /\d{4}/ }

# Get /posts/2012/07/?page=1
match "/posts/:year/:month", :to => "posts#index",
  :constraints => { :year => /\d{4}/, :month => /\d{1,2}/ }

# Get /posts/2012/07/slug-of-the-post
match "/posts/:year/:month/:slug", :to => "posts#show", :as => :post,
  :constraints => { :year => /\d{4}/, :month => /\d{1,2}/, :slug => /[a-z0-9\-]+/ }

So, I have to work with parameters in action indexand just get post by slug in action show(checking if date corct is an option):

# GET /posts?page=1
def index
  #render :text => "posts#index<br/><br/>#{params.to_s}"
  @posts = Post.order('created_at DESC').page(params[:page])
  # sould be more complicated in future
end

# GET /posts/2012/07/19/slug
def show
  #render :text => "posts#show<br/><br/>#{params.to_s}"
  @post = Post.find_by_slug(params[:slug])
end

Also I need to implement to_paramfor my model:

def to_param
  "#{created_at.year}/#{created_at.month}/#{slug}"
end

This is all that I learned from all the night searches in api / guide / SO.

But the problem is that for me more and more things arise that are worn for rails:

  • localhost/, , show, : year (sic!):

    No route matches {:controller=>"posts", :action=>"show", :year=>#<Post id: 12, slug: "*", title: "*", content: "*", created_at: "2012-07-19 15:25:38", updated_at: "2012-07-19 15:25:38">}
    
  • localhost/posts/2012/07/cut-test, :

    No route matches {:controller=>"posts", :action=>"show", :year=>#<Post id: 12, slug: "*", title: "*", content: "*", created_at: "2012-07-19 15:25:38", updated_at: "2012-07-19 15:25:38">}
    

, - , , , .

, , , URL , .

+5
2

post path post_path(post), , :as => :post routes.rb.

, , , , :

  • ,

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

    post_date_path("2012","12","end-of-the-world-is-near") .

    posts_path, posts_year_path("2012"), posts_month_path("2012","12"), .

    :as => :post , to_param , , ( active_admin ).

  • posts-controller.rb , . .

  • posts.rb , :

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

    to_param, , .

+5

routes.rb? , resources :posts, /posts/:id. , , , , - .

0

All Articles