没有 id 的 Rails 3 资源路由 [英] Rails 3 resource routing without an id

查看:17
本文介绍了没有 id 的 Rails 3 资源路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Rails 3 上创建一个博客应用程序,我想通过执行

I am creating a blog application on Rails 3, and I want to override the default show route generated for a post by doing

resources :posts, :except => :show

对于表演路线(如果我没有排除它),

Which generates, for the show route (had I not excluded it),

/post/:id

我希望我的路线看起来像这样,其中 url_title 是我的模型在 before_save 上生成的字符串,它删除非字母数字字符并用连字符替换空格.

I want my route to look like this instead, where url_title is a string generated by my model on before_save, where it removes non alphanumeric characters and replaces spaces with hyphens.

/:year/:month/:day/:url_title

我试图用这段代码来完成这个:

I'm trying to accomplish this with this bit of code:

match "/:year/:month/:day/:url_title", :to => "posts#show", :as => :post

理论上这应该允许我调用 post_path(@post)(其中 @post 是我的 post 类的一个实例),并且它应该能够整理出这条路线,并且它几乎作品.

In theory this should allow me to call post_path(@post) (where @post is an instance of my post class), and it should be able to sort this route out, and it almost works.

唯一的问题是它试图用年份替换帖子的 id.其他字段填写正确.我认为这是因为 rails 有一些默认行为,这使得它真的非常希望在 url 中包含 id,并且它不相信我使用我自己的唯一标识符(在这种情况下为 post.url_title).

The only problem is that it tries to substitute the id of the post in for the year. The other fields fill in correctly. I think this is happening because rails has some default behavior that makes it really, really want to have the id in the url, and it doesn't trust me to use my own unique identifier (post.url_title, in this case).

不过我可能是错的.任何人都有这种路由的经验,或者知道发生了什么?

I could be wrong about that though. Anyone have experience with this kind of routing, or know what's up?

推荐答案

您可以使用 to_param 来制作 rails 用途

You can use to_param to craft the rails uses

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_paramhttp://www.seoonrails.com/to_param-for-better-looking-urls.html

如果你走这条路,你会想要创建一个永久链接属性,并使用 Post.find_by_permalink(params[:id]) 而不是 Post.find(params[:id])

If you go this route, you'll want to create a permalink attribute, and use Post.find_by_permalink(params[:id]) rather than Post.find(params[:id])

这篇关于没有 id 的 Rails 3 资源路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆