如何在RESTful URL中使用slugs



根据当前的最佳实践,留言板上给定线程的RESTful URL应该如下所示:

http://domain/forum/threads/3

这也是一个常见的SEO实践,URL应该包含关键字(slug),所以也许上面的URL可以变成:

http://domain/forum/threads/3/title-of-this-particular-thread

现在,再次编辑这个线程,根据我在第一段中链接的指导方针,URL将是:

http://domain/forum/threads/3/edit

当有人以"编辑"为标题启动一个线程时,会发生什么?应该如何决定是显示还是编辑线程?

代替http://domain/forum/threads/3/title-of-this-particular-thread

你应该做http://domain/forum/threads/3-title-of-this-particular-thread

这将防止冲突,并且同样对SEO友好。有几种方法可以实现这一点,但最简单的方法是在模型中添加一个自动转换的to_param方法:

class Thread < ActiveRecord::Base
to_param
"#{id}-#{title}"
end
end

如果你需要更多的灵活性,或者不想在所有型号中重复,你可以使用friendly_id宝石。

最新更新