我希望我的网站网址看起来像这样:
- example.com/2010/02/my-first-post
我的帖子模型有slug字段(‘my-first-post’)和published_on字段(我们将从中扣除url中的年份和月份).
我希望我的Post模型是RESTful的,所以像url_for(@ post)这样的东西就像它们应该的那样工作,即:它应该生成上面提到的url.
有没有办法做到这一点?我知道你需要覆盖to_param并拥有map.resources:posts with:options选项设置,但我无法全部工作.
我几乎完成了,我90%在那里.使用resource_hacks plugin我可以做到这一点:
- map.resources :posts,:member_path => '/:year/:month/:slug',:member_path_requirements => {:year => /[\d]{4}/,:month => /[\d]{2}/,:slug => /[a-z0-9\-]+/}
- rake routes
- (...)
- post GET /:year/:month/:slug(.:format) {:controller=>"posts",:action=>"show"}
并在视图中:
- <%= link_to 'post',post_path(:slug => @post.slug,:year => '2010',:month => '02') %>
生成正确的example.com/2010/02/my-first-post链接.
我也想这样做:
- <%= link_to 'post',post_path(@post) %>
但它需要覆盖模型中的to_param方法.应该相当容易,除了事实,to_param必须返回String,而不是Hash,因为我喜欢它.
- class Post < ActiveRecord::Base
- def to_param
- {:slug => 'my-first-post',:month => '02'}
- end
- end
结果无法将Hash转换为String错误.
这似乎被忽略了:
- def to_param
- '2010/02/my-first-post'
- end
因为它导致错误:post_url无法从{:action =>“show”,:year =>#< Post id:1,title:(...)生成(它错误地将@post对象分配给:年份密钥).我对如何破解它毫无头绪.
解决方法
Rails 3.x和Rails 2.x的漂亮网址,不需要任何外部插件,但遗憾的是有点破解.
的routes.rb
- map.resources :posts,:except => [:show]
- map.post '/:year/:month/:slug',:controller => :posts,:action => :show,:year => /\d{4}/,:month => /\d{2}/,:slug => /[a-z0-9\-]+/
application_controller.rb
- def default_url_options(options = {})
- # resource hack so that url_for(@post) works like it should
- if options[:controller] == 'posts' && options[:action] == 'show'
- options[:year] = @post.year
- options[:month] = @post.month
- end
- options
- end
post.rb
- def to_param # optional
- slug
- end
- def year
- published_on.year
- end
- def month
- published_on.strftime('%m')
- end
视图
- <%= link_to 'post',@post %>
注意,对于Rails 3.x,您可能希望使用此路由定义:
- resources :posts
- match '/:year/:month/:slug',:to => "posts#show",:as => :post,:slug => /[a-z0-9\-]+/
是否有任何徽章可以回答您自己的问题?