我希望我的网站具有如下所示的 URL:
example.com/2010/02/my-first-post
我的Post
模型带有slug
字段('my-first-post')和published_on
字段(我们将从中扣除 url 中的年份和月份部分)。
我希望我的Post
模型是 RESTful 的,所以url_for(@post)
像它们应该的那样工作,即:它应该生成上述 url。
有没有办法做到这一点?我知道您需要覆盖to_param
并map.resources :posts
设置:requirements
选项,但我无法让它全部工作。
我几乎完成了,我已经完成了 90%。使用resource_hacks 插件我可以做到这一点:
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', :year => '2010', :month => '02'}
end
end
结果can't convert Hash into String
出错。
这似乎被忽略了:
def to_param
'2010/02/my-first-post'
end
因为它会导致错误:(post_url failed to generate from {:action=>"show", :year=>#<Post id: 1, title: (...)
它错误地将 @post 对象分配给 :year 键)。我对如何破解它一无所知。