【发布时间】:2011-01-16 12:44:05
【问题描述】:
我希望我的网站具有如下所示的 URL:
example.com/2010/02/my-first-post
我的Post 模型带有slug 字段('my-first-post')和published_on 字段(我们将从中扣除网址中的年份和月份部分)。
我希望我的 Post 模型是 RESTful 的,所以像 url_for(@post) 这样的东西应该可以正常工作,即:它应该生成上述 url。
有没有办法做到这一点?我知道您需要覆盖 to_param 并设置 map.resources :posts 并设置 :requirements 选项,但我无法让它全部工作。
我几乎完成了,我已经完成了 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', :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 键)。我对如何破解它一无所知。
【问题讨论】:
标签: ruby-on-rails url rest slug