更改从ID到用户名的设计路线

时间:2011-04-17 20:42:09

标签: ruby-on-rails-3 devise

我尝试使用帖子将路由更改为指向用户名。我知道这很简单,但由于某种原因我目前无法计算它。我也在设计文档页面上尝试过所有内容。

Drawing username routes

我只想让路由布局使用用户名而不是id而不是用户前缀。像:

http://example.com/username

而不是

http://example.com/users/1

1 个答案:

答案 0 :(得分:7)

class User < ActiveRecord::Base
  def to_param
    username
  end
end

在你的控制器中

@user = User.find_by_username(params[:id])

而不是

@user = User.find(params[:id])

这将使您的路线成为http://example.com/users/username

制作你想要的东西,你可以做路线:

resources :users, :path => '' do
  # nested resources...
end

所以,user_path(@user)将生成网址http://example.com/username 但这不是一个好习惯,因为它不是一个REST。我建议你留下像http://example.com/users/username

这样的网址