question about named route

Hi,

I have quetion about 'named route'.

I defined the following in routes.rb to use ':title' instead of ':id'.

  map.movie '/
movies/:title', :controller=>'movies', :action=>'show', :conditions=>{:method=>:get}

This seems to work fine, but 'movie_path()' still uses ':id' instead
of ':title'.

  movie = Movie.get(parms[:id])
  p movie_path(movie) #=> "/movies/1" (expected is "/movies/Avatar")

How to change 'movie_path()' to use ':title'?

you can use http://svn.techno-weenie.net/projects/plugins/permalink_fu/ plugin

I defined the following in routes.rb to use ‘:title’ instead of ‘:id’.

map.movie '/

movies/:title’, :controller=>‘movies’, :action=>‘show’, :conditions=>{:method=>:get}

This seems to work fine, but ‘movie_path()’ still uses ‘:id’ instead

of ‘:title’.

movie = Movie.get(parms[:id])

p movie_path(movie) #=> “/movies/1” (expected is “/movies/Avatar”)

How to change ‘movie_path()’ to use ‘:title’?

The reason this happens is that movie_path converts an object to a parameter using the to_param method of the object, rather than knowing what parameter the route wants.

So, there are two solutions:

class Movie

def to_param

name

end

end

movie_path(movie.title)

Depending on how many other paths rely on you passing a movie around, that will affect your decision. A little known third option is this:

class Movie

def to_param

“#{id}-#{name}”

end

end

That way you can just use the param :id in your path (and 1-Avatar will be converted to the integer 1 when searched using the :id field) but the title of the movie will be in the URLs for SEO purposes.

Cheers,

Andy

I think you’re solving a different problem than he asked for though. Permalink_fu is good for creating slugs, so if he had “Throw Momma From The Train” as a movie it would stop URLs like this:

http://example.com/movies/Throw Momma From The Train”

It’s a good point, using the title/name of the movie (that may have spaces) will break sooner or later, but he was asking about ids/names in parameters for named_routes.

Cheers,

Andy

bala and Andy,
Thank you very much!

I choosed to override to_param() as "#{id}-#{name}".

Thank you.