2011-01-20 68 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