我希望以这种格式获得用户个人资料的网址:mydomain.com/username
我已经开始在用户模型中实现它:
user.rb
before_create :create_permalink
.
.
def to_param
permalink
end
.
.
private
def create_permalink
self.permalink = username.downcase
end
users_controller.rb
def show
@user = User.find_by_permalink(params[:permalink])
end
的routes.rb
match "/:permalink", to: "users#show", via: 'get'
当我访问mydomain.com/username时,会显示用户个人资料,但当我通过user_path(current_user)
链接执行此操作时,我收到此错误
undefined method `username' for nil:NilClass
,网址为mydomain.com/user/username,我不想要。
如何编辑默认的rails路由并将用户路由编辑为我想要的格式?
routes.rb中:
Code::Application.routes.draw do
resources :users, except: [:edit, :show]
resources :sessions, only: [:new, :create, :destroy]
root 'pages#home'
match '/help', to: 'pages#help', via: 'get'
match '/about', to: 'pages#about', via: 'get'
match '/contact', to: 'pages#contact', via: 'get'
match '/signup', to: 'users#new', via: 'get'
match '/signin', to: 'sessions#new', via: 'get'
match '/signout', to: 'sessions#destroy', via: 'delete'
get '/:permalink', to: 'users#show', as: 'user'
get '/:permalink/edit', to: 'users#edit', as: 'edit_user'
end
仅删除as: 'user'
行并离开as: 'edit_user'
后,我运行了bundle exec rake routes | grep -i "user"
:
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
user PATCH /users/:id(.:format) users#update
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
signup GET /signup(.:format) users#new
GET /:permalink(.:format) users#show
edit_user GET /:permalink/edit(.:format) users#edit
答案 0 :(得分:0)
不要使用帮助方法,为路线命名:
get '/:permalink', to: 'users#show', as: 'user'
get '/:permalink/edit', to: 'users#edit', as: 'edit_user'
它更干净,你还有命名路线的所有优点
编辑:您的资源正在为更新操作
创建一个名为“用户”的路径user PATCH /users/:id(.:format) users#update
您有两种方法可以解决它:
1-最简单的(我会推荐这个):为这两条新路线使用另一个名称:
get '/:permalink', to: 'users#show', as: 'custom_user'
get '/:permalink/edit', to: 'users#edit', as: 'custom_edit_user'
现在你将这些操作称为“custom_user_path”和“custom_edit_user_path”,没有冲突
2-更复杂:用户资源的另一个名称
resource :users, except: [:edit, :show], as: 'old_users'
...
...
get '/:permalink', to: 'users#show', as: 'user'
get '/:permalink/edit', to: 'users#edit', as: 'edit_user'
这样你就可以使用user_path和edit_user_path,但是所有其他“user *”路由都必须改为“old_user * _path”,比如:而不是“new_user_path”你必须使用“new_old_user_path”。
我建议您使用第一个选项,检查所有代码并使用“custom_user_path”或“custom_edit_user_path”,您将完成