在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 (以及标记param的acts-as-taggable和页面param的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
endroutes.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帮助正常。
这是可行的(减去更新),但感觉很难看。有更好的办法吗?
发布于 2014-08-20 09:39:49
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这可能行不通(事实上,它可能不会),但我试图证明的是,我认为您最好将对params / year / month / title的处理分拆到控制器中。
https://stackoverflow.com/questions/25399736
复制相似问题