2015-08-28 49 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

相關問題