繁体   English   中英

如何在Rails 3中将Rails路由从controller /:id更改为controller /:name?

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

就像话题说的那样。 我想在Rails 3中将默认的controller /:id路由更改为controller /:name。在Rails 2中,您使用了命名路由,如下所示:

配置/ routes.rb中

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

备用命名路线

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

视图中URL规范的示例

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

但是我敢肯定,Rails 3中还有另一种(更好)的方式。

如果:name是对象的唯一标识符,则可以https://github.com/norman/friendly_id获得对ActiveRecord的常规永久链接支持。

仅按指定

has_friendly_id :name

你会自动像

http://example.com/states/washington

代替

http://example.com/states/4323454

如果您有location.name,则可以像这样link_to:

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

将为您提供url / locations /:name

相对于

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

这将为您提供/ locations /:id

不确定,但这可能会对您有帮助。

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

这和

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

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM