簡體   English   中英

Rails嵌套奇異資源路由

[英]Rails Nested Singular Resource Routing

我有一個簡單的用戶模型,帶有一個單一的嵌套Profile資源,因此在我的routes.rb中我有:

resources :users do
  resource :profile, :only => [:edit, :update, :show]
end

這會生成預期的路線:

edit_user_profile GET    /users/:user_id/profile/edit(.:format)  {:action=>"edit", :controller=>"profiles"}
     user_profile GET    /users/:user_id/profile(.:format)       {:action=>"show", :controller=>"profiles"}
     user_profile PUT    /users/:user_id/profile(.:format)       {:action=>"update", :controller=>"profiles"}

我創建了一個簡單的控制器更新方法來更新模型,然后在成功更新時重定向:

def update
  @profile = Profile.find_by_user_id(params[:user_id])
  @user = User.find_by_id(params[:user_id])

  respond_to do |format|
    if @profile.update_attributes(params[:profile])
      format.html { redirect_to( user_profile_path(@user, @profile), :notice => 'Profile was successfully updated.') }
    else
      # ...
    end
  end
end

問題是,一旦提交表單,表單就會重定向到mydomain.com/users/4/profile.22,其中22恰好是配置文件的ID。 顯然,這會使控制器混淆,因為路由將'22'解釋為格式。

我的問題是, 如何將其重定向到mydomain.com/users/4/profile呢? 我已經在redirect_to語句中嘗試了以下變體而沒有效果,它們都會導致相同的錯誤網址:

redirect_to( user_profile_path(@user), ... )
redirect_to( user_profile_path(@user, @profile), ... )
redirect_to([@user, @profile], ... )
redirect_to( @profile, ... )

更重要的是,在其他地方使用'user_profile_path(@user)'可以生成正確的URL。

有任何想法嗎? 哦,如果有幫助的話,我正在使用Rails 3.0.0和Ruby 1.9.2。

環顧四周后,生成更新的表單似乎有一個不正確的網址。 如果有人看到這個問題,那是因為我將表單設置為:

form_for [@user, @profile] do |f| ...

這導致表單操作具有不正確的URL(上面的違規表單)。 相反,我用過

form_for @profile, :url => user_profile_path(@user) do |f| ...

一切似乎都有效。

您應該重定向到user_profile_path(@user),因為您的路由表明它是:

/users/:user_id/profile(.:format)

如果你仔細觀察它,那么你會看到,只需要:user_id參數,你只需要路徑中的@user。

/users/:user_id/profile/:id(.:format)

如果您在routes.rb中有資源* s *:配置文件,那么這是正確的,那么您也可以在示例中使用您的路徑。

user_profile_path(@user)應該是正確的。 你肯定有人會回來mydomain.com/users/4/profile.22嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM