gpt4 book ai didi

ruby-on-rails-3 - 在 Rails 中通过用户名更正短 url 的路由

转载 作者:行者123 更新时间:2023-12-01 08:26:00 25 4
gpt4 key购买 nike

我正在尝试替换此类用户个人资料 View

/users/1

/用户名

我知道这意味着我需要检查各种碰撞。我咨询了以下类似的 SO 问题:

以下是我尝试过的各种失败的 routes.rb 路由定义,以及相关的错误:

  1. 匹配“/:username”=>“users#show”,通过:“get”

    这是错误:

    ActiveRecord::RecordNotFound in UsersController#show

    Couldn't find User without an ID

    app/controllers/users_controller.rb:7:in `show'

    这是我对应的 users_controller:

    6 def show
    7 @user = User.find(params[:id])
    8 end
  2. match "/:username"=> 'users#show', :as => :profile

    和上面一样的错误。

  3. 匹配 "/:username", :controller => "users/:id", :action => 'show'

     Routing Error

    uninitialized constant Users

    Try running rake routes for more information on available routes.
  4. 匹配 '/:username', :controller => 'users', :action => 'show'

    与 1 相同的错误。

  5. 匹配 '/:username',到:'users/:id',通过:'show'

    服务器没有启动。

  6. 匹配 "/:username"=> redirect("/users/:id")

    错误:

     ActiveRecord::RecordNotFound in UsersController#show

    Couldn't find User with id=:id

知道为什么我的路由工作方式与其他提出此问题的人不同吗?

更新

只是为了将这个问题从评论中移除,并将其更干净地放在问题中。通过下面的@Ryan Bigg 进行更改后,在创建新配置文件时,我在重定向到配置文件时遇到了路由问题。这是我的创建代码:

  def create
@user = User.new(params[:user])
if @user.save
session[:user_id] = @user.id
flash[:success] = "Thank you for signing up."
redirect_to ('/'+@user.username)
#redirect_to @user, notice: "Thank you for signing up!"
else
render "new"
end
end

这是我的 user.rb

def to_param
self.username
#username
end

但是,我认为应该与 to_param 更新一起使用的注释掉的重定向不起作用,而上面那个丑陋的骇人听闻的重定向却起作用。为什么 to_param 被覆盖,which worked for other people , 不在我的应用程序上工作?我的#update 和#edit 方法也不起作用,因为如果覆盖 to_param 没有解决这个问题,它们的重定向将转到“users/1/edit”而不是“username/edit”。

最佳答案

第一个是正确的,但没有用,因为您仍在尝试在 Controller 中执行类似的操作:

User.find(params[:username])

什么时候你应该这样做:

User.find_by_username!(params[:username])

第一个将尝试通过表的主键查找,而第二个将正确地查询用户名字段。

关于ruby-on-rails-3 - 在 Rails 中通过用户名更正短 url 的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11514723/

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