【问题标题】:How do I edit my Profile that is associated with User?如何编辑与用户关联的个人资料?
【发布时间】:2015-11-23 14:10:54
【问题描述】:

我创建了模型用户和模型配置文件。在我的主页上,我在下拉菜单导航栏中有一个链接,该链接指向编辑个人资料。 我面临的问题是“没有路由匹配 {:action=>"edit", :controller=>"profiles", :id=>nil} 缺少必需的键:[: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 是 Profile#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

【问题讨论】:

    标签: ruby-on-rails hyperlink routes url-routing link-to


    【解决方案1】:

    你试过了吗?

     edit_profile_path(id: @profile.id)
    

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

    【讨论】:

    • 谢谢@JohnPollard!我最终使用了 edit_profile_path(current_user.id)。感谢您抽出宝贵时间帮助我。
    【解决方案2】:

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

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

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

    【讨论】:

    • 谢谢@KMRakibul!我感谢你帮助我。 current_user 方法有效!
    【解决方案3】:

    需要注意的几点(这可能是解决您的问题的关键)。

    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

      在你看来:

      &lt;%= link_to edit_profile_path(current_user.profile) %&gt;

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

    【讨论】:

    • 谢谢@Hristo!感谢您抽出宝贵时间帮助我。我使用了您的建议来使用 current_user 并将其应用于路线。我的应用现在允许用户编辑他们的个人资料。
    猜你喜欢
    • 2012-09-30
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多