如何编辑与用户关联的个人资料?

How do I edit my Profile that is associated with User?

我创建了模型用户和模型配置文件。在我的主页上,下拉菜单导航栏中有一个 link,link 用于编辑个人资料。 我面临的问题是 "No route matches {:action=>"edit", :controller=>"profiles", :id=>nil} missing required keys: [:id]".

编辑页面的路径是 "edit_profile_path",带有动词 GET 和 URI 模式“/profiles/:id/edit(.:format)”。我很难插入 "id"。以下是我在我的应用程序中的代码。

在模型配置文件中我有:

class Profile < ActiveRecord::Base
    belongs_to :user, dependent: :destroy
end

在模型用户文件中我有:

class User < ActiveRecord::Base
  has_one :profile
end

配置文件有很多属性,但其中之一是 "user_id",它是一个等于用户 ID 的整数。所以 ID#5 的用户 #5 是配置文件#5 的所有者。 这是我在视图文件中的代码:

<li><%= link_to "Edit Profile", edit_profile_path(@profile) %></li>

关于上面的代码,我尝试在括号内插入不同的代码,来自@profile.id、@profile、@user.id 和@user。但是没有效果。

我创建了一个配置文件控制器,我认为(但我不确定)我的问题来自 profiles_controller 文件。 这是我的代码有:

class ProfilesController < ApplicationController
  before_action :authenticate_user!
  before_action :set_profile, only: [:edit, :update]

  def edit
  end

  def new
    @profile = Profile.new
  end

  def create
    @profile = Profile.new(profile_params)
    @profile.user_id = current_user.id
    if @profile.save
      redirect_to welcome_path
    else
      render 'new'
    end
  end

  def update
    @profile.update(profile_params)
    redirect_to welcome_path
  end

    private
      def set_profile
        @profile = Profile.find(params[:id])
      end
  end

你试过了吗?

 edit_profile_path(id: @profile.id)

你也把这条路线放在你的路线文件中了吗?

您收到此错误是因为在您看来,您的 @profilenil 中。 因此,您必须在视图中获取 current_profile,以便您可以转到该配置文件的编辑页面。

如果您已经可以访问 current_user 辅助方法,那么在您看来,您可以简单地执行以下操作:

<li><%= link_to "Edit Profile", edit_profile_path(current_user.profile) %></li>

注意几点(可能是解决你问题的关键)。

  1. 你有一对一的关系,用户只有在登录后才能访问他的个人资料。因为你已经有一个(可能正常工作的)current_user方法,一直用它。

    def new current_user.build_profile end

    def create current_user.build_profile(profile_params) #etc end

  2. 这也是获取用户个人资料的合乎逻辑的方式

    private def set_profile @profile = current_user.profile end

    在您看来:

    <%= link_to edit_profile_path(current_user.profile) %>

我认为这在您的代码中更有意义并且更易读。此外,我认为这种方法可以避免很多错误,例如您现在遇到的错误。