3

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 - the 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 ...

dnewman
  • 275
  • 3
  • 11

1 Answers1

4

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

Unixmonkey
  • 18,485
  • 7
  • 55
  • 78
  • thanks but i want to figure out how to get the url to be: /posts/345/the-great-concept not /posts/345-the-great-concept. the latter i already know how to do. – dnewman Apr 03 '11 at 22:53
  • @dnewman Updated my answer. Its more complex, but accurate to your specifications. Hope it helps! – Unixmonkey Apr 04 '11 at 01:38
  • hey man - i appreciate the help ... yeah i was hoping to not have to rewrite all my view link_to paths from the existing post_path(@post). it's a pretty big app. was looking for some way for the app to just ignore like the following /posts/:id/*ignore/[more stuff]. i think i need to really dig deeper into routes. – dnewman Apr 04 '11 at 16:52
  • You don't actually have to change those routes, but I figured you'd want to for consistency. You might be able to write your own post_path and post_url helpers that automatically figure out the slug part: def post_url(post); slug_path(post, :slug => post.slug); end – Unixmonkey Apr 04 '11 at 17:14