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’?


regards,
makoto

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

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

On 14 April 2010 09:29, bala kishore pulicherla [email protected]
wrote:

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

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.

regards,
makoto

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs