2011-01-20 67 views
2

在嵌套資源路由時遇到一些麻煩。我試圖做的是鏈接到用戶的個人資料頁面進行編輯。在我看來,它是寫爲:Rails 3 - 嵌套資源路由 - 一對一關係

<%= link_to "Edit Profile", edit_user_profile_path(current_user) %> 

與錯誤了:

No route matches {:action=>"edit", :controller=>"profiles", :user_id=>#<User id: 1, email: "EDITEDOUT", hashed_password: "EDITEDOUT", created_at: "2011-01-20 18:30:44", updated_at: "2011-01-20 18:30:44">} 

在我的routes.rb文件,它看起來像這樣:

resources :users do 
    resources :profiles, :controller => "profiles" 
end 

我檢查了我的耙路線,它給了我作爲一個有效的選擇:

edit_user_profile GET /users/:user_id/profiles/:id/edit(.:format) {:action=>"edit", :controller=>"profiles"} 

我可以手動導航到。爲了獲得良好的措施,這是我的控制器的證明:

class ProfilesController < ApplicationController 
    def edit 
    @user = current_user 
    @profile = current_user.profile 
    end 

    def update 
    @user = current_user 
    @profile = current_user.profile 


    respond_to do |format| 
     if @profile.update_attributes(params[:profile]) 
     format.html { redirect_to(orders_path, :notice => "Your profile has been updated.") } 
     format.xml { head :ok } 
     else 
     format.html { render :action => "edit" } 
     format.xml { render :xml => @profile.errors, :status => :unprocessable_entity } 
     end 
    end 
    end 
end 

不管怎樣,我一直有一些問題跟蹤下來。任何指針都會有所幫助。對於我的數據庫設計,配置文件屬於一對一關係的用戶。我希望這只是一些新東西,我不會注意到一組新的眼睛可能會有所幫助。

回答

2

如果你仔細觀察你的路線,你會發現它預計:user_id:id。後者在這種情況下是指用戶配置文件。

爲了告訴你想要的Rails特定的個人主頁上,你必須同時指定用戶,並在您的鏈接配置文件,像這樣:

edit_user_profile_path(current_user, @profile) 

現在,Rails會使用第一個參數(current_user)爲路由的:user_id部分,第二個參數爲:id

+0

感謝一噸豐特康德!我非常感謝幫助。 – Kombo 2011-01-21 01:42:36