我尝试使用帖子将路由更改为指向用户名。我知道这很简单,但由于某种原因我目前无法计算它。我也在设计文档页面上尝试过所有内容。
我只想让路由布局使用用户名而不是id而不是用户前缀。像:
而不是
答案 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
这样的网址