我正在Rails 3上创建一个blog应用程序,并希望通过执行以下操作来覆盖为帖子生成的默认show route
resources :posts, :except => :show
它为show route生成(如果我没有排除它),
/post/:id
我希望我的路径看起来像这样,其中url_title是我在before_save上的模型生成的字符串,它删除非字母数字字符并用连字符替换空格。
/:year/:month/:day/:url_title
我试着用下面这段代码来实现这一点:
match "/:year/:month/:day/:url_title", :to => "posts#show", :as => :post
从理论上讲,这应该允许我调用post_path( @post ) (其中@ post是我的post类的一个实例),并且它应该能够对此路由进行排序,并且它几乎可以工作。
唯一的问题是它试图用职位的id替换年份。其他字段正确填写。我认为这是因为rails有一些默认行为,这使得它非常非常希望在url中包含id,并且它不信任我使用自己的唯一标识符(在本例中是post.url_title)。
不过,我可能是错的。有没有人有这种路由的经验,或者知道怎么回事?
发布于 2011-03-16 22:27:49
您可以使用to_param来手工编写rails使用的
class Post < ActiveRecord::Base
...
def to_param
"#{year}/#{month}/#{day}/#{title.parameterize}"
end
end
更多信息:http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-i-to_param和http://www.seoonrails.com/to_param-for-better-looking-urls.html
如果使用此路径,则需要创建一个固定链接属性,并使用Post.find_by_permalink(params[:id]
而不是Post.find(params[:id])
发布于 2011-03-16 22:24:34
您应该像这样使用路径
post_path(@post, :year => 2010, :month => 3, :day => 16)
或
post_path(@post, :year => @post.created_at.year, :month => @post.created_at.month, :day => @post.created_at.day)
https://stackoverflow.com/questions/5326483
复制相似问题