Gag*_*gan 10 routes named ruby-on-rails-3
地狱自由
我想在用户的显示页面中显示用户名而不是user_id.
例如,
数据库中存在名为harry的用户的usr_id 300.那怎么展示
代替
在网址中.
这可以在路线文件中完成吗?
谢谢
cor*_*ard 15
这通常被称为虚荣URL,有点谨慎,你可以很容易地处理这个问题.第一...
在你的路线:
# the simple case
get '/:username' => 'users#show', :constrain => { :username => /[a-zA-Z-]+/ }
# ...with vanity_url_path(@user) helpers
get '/:username' => 'users#show', :as => 'vanity_url'
# or routing something more complicated with all the default resourceful routes
resources :users, :path => '/:username'
# or even just defining a bunch of routes for users with this format
controller :users, :path => '/:username' do
get '/profile', :action => :profile #=> /johnsmith/profile => UsersController#profile
end
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,:constrain
为了清楚起见,我避免为每个路由重复选项.您需要调整正则表达式以匹配您的用户名,然后确保在您使用的任何路径上都有它.
如果这将是从应用程序中访问用户的默认方式(即,不仅仅是访问用户配置文件的便捷方式),您还需要覆盖to_param
Users模型上的方法.这允许您使用url_for
助手,form_for @user
而无需指定其他参数.
class User
def to_param
username
end
end
Run Code Online (Sandbox Code Playgroud)
另一个快速提示:如果你正在玩你的路线并尝试做除基础之外的任何事情,请务必$ rake routes
经常从命令行调用以查看Rails当前识别的路线.清理你不需要的东西也很好.;)