开发者

How do i change Rails routing from controller/:id to controller/:name in Rails 3?

开发者 https://www.devze.com 2023-01-07 05:25 出处:网络
Just as the topic say. I want to change the default controller/:id routing to controller/:name instead in Rails 3. In Rails 2 you used named routing with something like this:

Just as the topic say. I want to change the default controller/:id routing to controller/:name instead in Rails 3. In Rails 2 you used named routing with something like this:

config/routes.rb

map.location 'location/:name', 
  :controller => 'your_开发者_运维问答controller', :action => 'your_action'

alternate named route

map.location 'goto/:name', :controller => 'location', :action => 'your_action'

examples of URL specification in a view

<%= link_to 'foo', location_url({:name => 'foo'}) %>
<%= link_to 'bar', location_path({:name => 'bar'}) %>

But i'm sure there is another (better) way in Rails 3.


If the :name is a unique identifier of the object, you can you https://github.com/norman/friendly_id for general permalink support for ActiveRecord.

Just by specified

has_friendly_id :name

you'll get automatically routing like

http://example.com/states/washington

instead of

http://example.com/states/4323454


Not sure but may this would help you.

match 'user_delete/:name', :to => 'sessions#destroy'

this is same as

map.user_delete '/user_delete/:name', :controller => 'sessions', :action => 'destroy'


Try this:

match 'location/:name' => 'your_controller#your_action', :as => location


If you have location.name, then you could link_to it like this:

<%= link_to 'foo', location_path(location.name) %>

will give you the url /locations/:name

as opposed to

<%= link_to 'foo', location %> #same as <%= link_to 'foo', location_path(location) %>

which will give you /locations/:id

0

精彩评论

暂无评论...
验证码 换一张
取 消