Renaming Routes (map, Link_to, To_param) In Rails

- 1 answer

I'm having a little issue...I setup a rails application that is to serve a german website. To make use of Rails' internal pluralization features, I kept all my models in english (e.g. the model "JobDescription"). Now, if I call "", I get all my far, so good. Because I didn't want the english term "job_descriptions" in my url, I put the following into my routes.rb

map.german_term '/german_term', :controller => 'job_descriptions', :action => 'index'
map.german_term '/german_term/:id', :controller => 'job_descriptions', :action => 'show'

If I call "" or "" I get all my job_descriptions, which is fine.

However, to make the URL more SEO friendly, I'd like to exchange the id for a more userfriendly slug in the URL. Thus, I put the following in my job_description.rb:

def to_param
"#{id}-#{name.gsub(/[^a-z0-9]+/i, '-')}"

which, whenever I use "job_description_path" in any link_to method, renders my URLs out to something like "http://mysite/job_descriptions/13-my-job-description-title".

However, and this is where I'm stuck, I'd like to get "http://mysite/german_term/13-my-job-description-title". I already tried to exchange the "job_description_path" with "german_term_path" in the link_to code, but that only generates "http://mysite/german_term/13". Obviously, to_param isn't called. One workaround I found is to build the link with:

<%= link_to, german_term_path(job_description.to_param) %>

But that's rather tedious to change all the link_to calls in my code. What I want is to replace "job_description" by "german_term" whenever it occurs in a URL.

Any thoughts?!?





I think you're going to need to use the restful route helpers to get what you want.

In that case, it wouldn't take much re-factoring (assuming you've mapped JobDescriptions as a resource). Leave your to_param as is and change your JobDescriptions route to something like the following:

map.resources :job_descriptions, :as => 'german_term'

Hope this helps!