我希望我的网站具有如下所示的 URL:
example.com/2010/02/my-first-post
我有我的Post
模型与slug
字段('我的第一篇文章')和published_on
字段(我们将从中扣除 url 中的年份和月份部分)。
我想要我的Post
模型是 RESTful 的,所以像url_for(@post)
像他们应该的那样工作,即:它应该生成上述 url。
有没有办法做到这一点?我知道你需要覆盖to_param
并有map.resources :posts
with :requirements
选项集,但我无法让它全部工作。
我已经快完成了,已经完成了 90%。使用资源黑客插件 http://github.com/stengland/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.
我也希望这个工作:
<%= link_to 'post', post_path(@post) %>
但它需要覆盖to_param
模型中的方法。应该相当容易,除了以下事实:to_param
必须返回String
, not Hash
如我所愿。
class Post < ActiveRecord::Base
def to_param
{:slug => 'my-first-post', :year => '2010', :month => '02'}
end
end
结果是can't convert Hash into String
error.
这似乎被忽略了:
def to_param
'2010/02/my-first-post'
end
因为它会导致错误:post_url failed to generate from {:action=>"show", :year=>#<Post id: 1, title: (...)
(它错误地将 @post 对象分配给 :year 键)。我对如何破解它有点一无所知。