Rails 4 Blog /:year /:month /:带有干净路由的标题

时间:2014-08-20 08:08:11

标签: ruby-on-rails routing friendly-id

在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(以及acts-as-taggable用于标记参数和kaminari用于页面参数)尝试了以下操作:

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

使用过的资源可以正常使用路径和网址助手。

这可行(减去更新),但感觉非常难看。还有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

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

-

<强>蛞蝓

要创建slu,,您只能使用friendly_id的标题:

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

这可能无法开箱即用(事实上,它可能会赢得),但我试图证明的是,我认为你可以更好地分配你对params / year / month / title进入您的控制器