Rails 4 Blog /: year /: month /: header with pure routing

There is another cleaner way to reach routes in Rails 4, for example:

/blog/2014/8/blog-post-title
/blog/2014/8
/blog/2014
/blog/2014/8/tags/tag-1,tag-2/page/4
/blog/new OR /blog_posts/new

I tried to use FriendlyId(as well as acts-as-taggablefor the tag parameter and kaminarifor the page parameter):

blog_post.rb

 extend FriendlyId
 friendly_id :slug_candidates, use: [:slugged, :finders]

 def to_param
   "#{year}/#{month}/#{title.parameterize}"
 end

 def slug_candidates
 [
    :title,
    [:title, :month, :year]
 ]
 end

 def year
   created_at.localtime.year
 end

 def month
   created_at.localtime.month
 end

routes.rb

  match '/blog_posts/new', to: 'blog_posts#new', via: 'get'
  match '/blog_posts/:id/edit', to: 'blog_posts#edit', via: 'get'
  match '/blog_posts/:id/edit', to: 'blog_posts#update', via: 'post'
  match '/blog_posts/:id/delete', to: 'blog_posts#destroy', via: 'destroy'
  match '/blog(/page/:page)(/tags/:tags)(/:year)(/:month)', to: 'blog_posts#index', via: 'get'
  match '/blog/:year/:month/:title', to: 'blog_posts#show', via: 'get'
  resources 'blog', controller: :blog_posts, as: :blog_posts

Resources used can contain both regular and URLs.

It works (minus the update), but it feels very ugly. Is there a better way?

+4
source share
1 answer

Friendly_ID

, , /:year/:month/:tags - :

#config/routes.rb
scope "/blog" do
   resources :year, controller :blog_posts, only: :show, path: "" do
      resources :month, controller : blog_posts, only: :show, path: "" do
         resources :title, controller: blog_posts, only: :show, path: ""
      end
   end
end
resources :blog_posts, path: :blog -> domain.com/blog/new

, , Rails (domain.com/blog/...) blog_posts#show

:

#app/controllers/blog_posts_controller.rb
Class BlogPostsController < ApplicationController

   def show
      case true
         when params[:year].present?
           @posts = Post.where "created_at >= ? and created_at < ?", params[:year]
         when params[:month].present?
           @posts = Post.where "created_at >= ? and created_at < ?", params[:month]
         when params[:id].present?
           @posts = Post.find params[:id]
      end
   end

end

#app/views/blog_posts/show.html.erb
<% if @posts %>
  <% @posts.each do |post| %>
    <%= link_to post.title, blog_post_path(post) %>
  <% end %>
<% end %>

<% if @post %>
   <%= link_to post.title, blog_post_path(post) %>
<% end %>

-

, friendly_id:

#app/models/blog_post.rb
Class BlogPost < ActiveRecord::Base
   extend FriendlyId
   friendly_id :title, use: [:slugged, :finders]
end

( , , ), , , , , / year/month/title

+2

All Articles