gpt4 book ai didi

ruby-on-rails - Rails 4 - 从/user/:id to/:username 更改 URL

转载 作者:太空宇宙 更新时间:2023-11-03 18:10:46 24 4
gpt4 key购买 nike

我有一个 Controller pages#dashboard,我已将其设置为 routes.rb 中的 user_root

devise_for :users, controllers: { registrations: 'registrations' }
devise_scope :user do
get "/signup" => "devise/registrations#new"
get "/login" => "devise/sessions#new"
get "/logout" => "devise/sessions#destroy"
get "/:id" => "users#dashboard", :as => "user_root", :id => :username
end

我希望 URL 为 http://my_app.com/current_user_username

我已将 user.rb 模型中的 to_param 设置为:

def to_param
username
end

当我有一个链接时,这工作正常:

<%= link_to "MY ACCOUNT", user_root_path(current_user) %>

但在初始登录时,URL 是:http://my_app.com/username (明确地说“用户名”)而不是 http://my_app.com/current_user_username

我尝试将 to_param 设置为:

def to_param
"#{username}"
end

并且还尝试将我的 route.rb 设置为:

get "/:id" => "users#dashboard", :as => "user_root", :id => :username, :via => :get

这些都没有解决问题。

环境:Rails 4.2.5、Ruby 2.3.0、Devise gem 3.5.3

如有任何帮助,我们将不胜感激。

最佳答案

您可以简单地在 routes.rb 中的所有内容之上添加另一条路线:

get "/:username" => "users#dashboard", :as => "user_root"
devise_for :users, controllers: { registrations: 'registrations' }
devise_scope :user do
get "/signup" => "devise/registrations#new"
get "/login" => "devise/sessions#new"
get "/logout" => "devise/sessions#destroy"
get "/:id" => "users#dashboard", :as => "user_root", :id => :username
end

然后你需要通过这样的方式找到用户:

    @user = User.find_by(username: params[:username])

关于ruby-on-rails - Rails 4 - 从/user/:id to/:username 更改 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34603825/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com