Reputation: 6896
An application I am working on in Rails 3 has a City model. Each City has a "name" column. I want this City.name to be the base url.
For example, with the City Name "Los Angeles": http://myapp.com/los-angeles.
If I use
match '/:name' => "cities#show"
resources :cities
I can get http://myapp.com/Los%20Angeles, but I need it to be 'los-angeles'. I assume I need to change the to_params in the city.rb file.
Additionally, what should my link_to look like when this is working? Right now I am trying
<%= link_to "View", city_path(:name => @city.name) %>
And that is giving me this error:
No route matches {:action=>"destroy", :name=>"Los Angeles", :controller=>"cities"}
Finally, you should note that I plan on nesting resources underneath the City in the routes so that I end up with urls like http://myapp.com/los-angeles/messages/message-content-using-to-param
etc..
Any advice you could give would be greatly appreciated!
Upvotes: 0
Views: 1343
Reputation: 21784
The method described here would be one approach. Overriding to_param
is also described in the Rails docs.
Add this to your City model.
def to_param
"#{self.name_for_url}"
end
def name_for_url
self.name.gsub(/^A-Z0-9\-_/i,'')
end
This will cause city_path(@city)
to provide /cities/los-angeles
If you want City to be your root controller, in routes.rb:
map.root :controller => 'city'
Now, http://myapp.com/los-angeles should work.
Upvotes: 1
Reputation: 64137
I personally use Friendly Id to handle pretty URLs with hooks into ActiveRecord(really nice by the way). This gem has nested resource support as well.
Upvotes: 1