2015-08-28 53 views
1

我创建了模型用户和模型配置文件。在我的主页上,我在链接到编辑配置文件的dropmenu导航栏中有一个链接。 我面对的问题是“没有路线匹配{: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的整数。因此#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 

回答

1

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

如果您已经拥有访问您current_user helper方法,那么,在你看来,你可以简单地做:

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

谢谢@KMRakibul!我感谢你帮助我。 current_user方法起作用! – Mauricio

0

你试过了吗?

edit_profile_path(id: @profile.id) 

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

+0

谢谢@JohnPollard!我结束了使用edit_profile_path(current_user.id)。我很感激你花时间帮助我。 – Mauricio

1

有几件事情需要注意(可能的关键,解决你的问题)。

  1. 你有一个1对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) %>

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

+1

谢谢@Hristo!我很感激你花时间帮助我。我用你的建议来使用current_user,并将其应用到路由。我的应用现在允许用户编辑他们的个人资料。 – Mauricio

相关问题