开发者

Rails url needing posts/:id/the-name-of-post

I would like my rails url to look like:

/posts/345/the-great-concept

when i use the following in my posts model,

def to_param
   "#{id}/#{name.parameterize.downcase}"
end

the urls look great upon mousover in the browser. and function correctly. however, once the page is loaded in the browser url it looks like:

/posts/345%2Fthe-great-concept

and to be clear, the "name" is just for good looks - th开发者_开发知识库e post is retrieved only by id. also i do not want to use a database slug approach.

how should i better approach this?

ps. don't want "/posts/345-the-great-concept" either ...


Its escaped because its not part of the path, but a param, so it needs to be escaped or you will be on the wrong uri.

def to_param
  "#{id}-#{name.parameterize.downcase}"
end

edit: Okay, so the slash is indeed important; Here's how to tackle it:

Create a custom route for that:

# in config/routes.rb
resources :posts
match '/posts/:id/:slug' => 'posts#show', :as => :slug

Then create your slug method:

# in app/models/post.rb
def slug
  title.parameterize.downcase
end

Then change your routes to the show action so the link to the fancy url:

# in any link to show; redirect after create, etc..
link_to slug_path(@post, :slug => @post.slug)

I created an app to test all this out, if interested, you can check it out at: https://github.com/unixmonkey/Pretty-Path

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜