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

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

问题描述

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

  resources:posts,:except => :show 

哪个生成了显示路线(如果没有排除的话)

  / post /:id 

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

  /:年/:月/:日/: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)。 / p>

我对此可能是错的。任何人都具有使用这种路由的经验,或者知道发生了什么?

解决方案

您可以使用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 和< a href = http://www.seoonrails.com/to_param-for-better-looking-urls.html rel = noreferrer> http://www.seoonrails.com/to_param-for-better-looking- urls.html



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


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

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

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.

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?

解决方案

You can use to_param to craft the rails uses

class Post < ActiveRecord::Base
  ...
  def to_param
    "#{year}/#{month}/#{day}/#{title.parameterize}"
  end
end

More info: http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-i-to_param and http://www.seoonrails.com/to_param-for-better-looking-urls.html

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天全站免登陆