ruby-on-rails – Rails 4 Blog /:year /:month /:带有干净路由的标题

在Rails 4中有另一种更简洁的方法来实现路由,例如:

/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

我已尝试使用FriendlyId进行以下操作(以及用于标记参数和kaminari用于页面参数的act-as-taggable):

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

使用过的资源可以正常使用路径和URL帮助程序.

这工作(减去更新),但感觉非常难看.有没有更好的办法?

最佳答案 Friendly_ID

我认为你的主要问题是你试图将你的/:year /:month /:标签保存在一组参数中 – 你更适合单独发送它们,并根据需要构建资源:

#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 action处理它们

这是我如何处理:

#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 %>

蛞蝓

要创建slug,您就可以使用friendly_id的标题:

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

这可能不是开箱即用(实际上,它可能不会),但我想证明的是,我认为你最好将你的params /年/月/标题的处理分成你的调节器

点赞