views:

31

answers:

2

Hi,

I am trying to get my urls to look like this:

example.com/posts/id_of_post/title_of_post

I have this in my controller:

match ':controller/:id/:link', :controller => 'posts', :action => 'show'

Say I have a list of posts.. how can I link to them?

<%= link_to 'Show', post %>

Just gives the usual /posts/id

On another note, at the minute I am making a url-friendly link when a post is created and storing it in the database. Would it be better to create on the fly? Is that possible/better?

I saw this in an answer to another question:

def to_param
  normalized_name = title.gsub(' ', '-').gsub(/[^a-zA-Z0-9\_\-\.]/, '')
  "#{self.id}-#{normalized_name}"
end

That would work if I could change the - to a /. Possible?

+1  A: 

I recommend just doing this instead of the gsub stuff:

def to_param
  "#{self.id}-#{title.parameterize}"
end

Downside is that if the title changes, the URL changes. Which is a downer.

So a lot of implementations will do

before_create :permanize

def permanize
  permalink = title.parameterize
end

def to_param
  "#{self.id}-#{permalink}"
end
Jesse Wolgamott
Is there anyway to do this with a '/' instead of a '-' between the id and the permalink? '%2f% displays a '/' when you rollover but when you click it changes to a '%2f' and doesn't work. In Firefox anyway..
GreenRails
No, not using to_params. What you'll want is match ':controller/:id/:link', :controller => 'posts', :action => 'show', :as=>:post_link ...... <%= link_to 'Show', post_link_path(@post, :link=>@post.permaname"%>
Jesse Wolgamott
Is there a way to define length with parameterize?
GreenRails
No, you'll need to use another ruby method to only take the first n characters that parameterize returns
Jesse Wolgamott
A: 

This is what I did:

I added this to my post#create:

@post.link = (@post.title.parameterize)

I will give the user the option to edit the title for up to 5 mins after posting.

My route:

match "/posts/:id/:link" => "posts#show", :as => "story"

and my index view for posts

<%= link_to 'Show', story_url(post, post.link) %>
GreenRails