Rails 3 resource routing without an id

一曲冷凌霜 提交于 2019-11-28 22:43:50

问题


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?


回答1:


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])




回答2:


you should use path like this

post_path(@post, :year => 2010, :month => 3, :day => 16)

or

post_path(@post, :year => @post.created_at.year, :month => @post.created_at.month, :day => @post.created_at.day)


来源:https://stackoverflow.com/questions/5326483/rails-3-resource-routing-without-an-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!