【问题标题】:Rails 3 - Nested Resources Routing - One to One relationshipRails 3 - 嵌套资源路由 - 一对一关系
【发布时间】:2011-01-20 23:22:49
【问题描述】:

在某些嵌套资源路由方面遇到了一些问题。我想要做的是链接到用户的个人资料页面以进行编辑。在我看来,它写成:

<%= 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  

我检查了我的 Rake 路线,它给了我一个有效的选项:

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

不管怎样,我在追踪这件事时遇到了一些问题。任何指针都会有所帮助。对于我的数据库设计,配置文件属于一对一关系的用户。我希望这只是一些新事物,我没有注意到新的眼睛可能会有所帮助。

【问题讨论】:

    标签: ruby-on-rails-3 routing nested-resources


    【解决方案1】:

    如果您仔细查看您的路线,您会发现它需要 :user_id:id。在这种情况下,后者指的是用户个人资料。

    为了告诉 Rails 您需要该特定配置文件,您必须在链接中指定用户和配置文件,如下所示:

    edit_user_profile_path(current_user, @profile)
    

    现在,Rails 将第一个参数 (current_user) 用于路由的 :user_id 部分,将第二个参数 (@profile) 用于 :id

    【讨论】:

    • 非常感谢冯康拉德!非常感谢您的帮助。
    猜你喜欢
    • 2011-05-23
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多