gpt4 book ai didi

ruby-on-rails-3 - 屏蔽 :id 的 Rails3 奇异路由

转载 作者:行者123 更新时间:2023-12-02 07:10:58 25 4
gpt4 key购买 nike

2.5 Singular Resources 下的 Rails 指南中,它指出

Sometimes, you have a resource that clients always look up without referencing an ID. For example, you would like /profile to always show the profile of the currently logged in user. In this case, you can use a singular resource to map /profile (rather than /profile/:id) to the show action.

所以我尝试了这个例子:

match "profile" => "users#show"

但是,当我尝试转到 profile_path 时,它会尝试重定向到以下位置,其中 id = :id:

/profile.id

这代表两个问题:

  1. 我根本不想显示 id,我认为这是一种屏蔽 id 的路由模式
  2. 使用此方法会导致以下错误。当我尝试请求 user_path 时,它也会导致此错误。

错误:

ActiveRecord::RecordNotFound in UsersController#show

Couldn't find User without an ID

我想这是因为传递的参数看起来像这样:

{"controller"=>"users", "action"=>"show", "format"=>"76"}

我是否正确使用单一资源?

我的用户 Controller :

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

respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @user }
end
end

我的路线:

  resources :users
match "profile" => "users#show"

最佳答案

首先,如果您想使用profile_urlprofile_path,您必须像这样使用:as:

match "/profile" => "users#show", :as => :profile

你可以找到解释here .

其次,在您的 Controller 中,您依靠 params[:id] 来找到您正在寻找的用户。在这种情况下,没有 params[:id],因此您必须重写您的 Controller 代码:

def show
if params[:id].nil? && current_user
@user = current_user
else
@user = User.find(params[:id])
end

respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @user }
end
end

关于ruby-on-rails-3 - 屏蔽 :id 的 Rails3 奇异路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5934365/

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