2016-03-01 50 views
0

我目前正在編寫代碼來爲登錄到我的應用程序的每個用戶構建一個個人資料頁面。但是我花了好幾個小時,似乎無法弄清楚這一點。請原諒我缺乏知識,我是鐵軌初學者,仍在學習。沒有路線匹配的個人資料頁面

我希望應用程序能夠查看和編輯他們自己的配置文件。現在,當登錄到應用程序時,它提供了「無路由匹配{:動作=>」顯示「,:控制器=>」配置文件「,:ID =>無}缺少所需密鑰:[:id]」

_navigation_links.html.erb

<% if user_signed_in? %> 
    <li><%= link_to('Sign Out', destroy_user_session_path, :method => :delete) %></li>  
    <li><%= link_to "View Profile", profile_path(@profile) %></li> 
    <li><%= link_to 'Edit', edit_profile_path(@profile) %></li> 
<% else %> 
    <li><%= link_to "Sign Up", new_user_registration_path %></li> 
    <li><%= link_to "Sign In", new_user_session_path %></li> 
<% end %> 

profiles_controller.rb

class ProfilesController < ApplicationController 
    before_action :find_profile, only: [:show, :edit, :update, :destroy] 
    before_action :authenticate_user! 

def index 
    @profiles = Profile.all 
end 

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

def new 
    @profile = current_user.profile.build 
end 

def edit 
end 

def create 
    @profile = Profile.new(profile_params) 

    @profile.save 
    redirect_to @profile 
end 

def update 
    @profile = Profile.find(params[:id]) 
if @profile.update(profile_params) 
    redirect_to @profile 
    else 
    render 'edit' 
    end 
end 

private 

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

def profile_params 
    params.require(:profile).permit(:id, :name, :summary, :birthday, :user_id) 
end 
end 

的routes.rb

Rails.application.routes.draw do 
    devise_for :users 
    resources :contacts, only: [:new, :create] 
    resources :visitors, only: [:new, :create] 
    root to: 'visitors#new' 

    resources :posts 
    resources :profiles 


end 

從我一個當用戶登錄到應用程序時,理解應用程序無法找到配置文件頁面的ID。我猜測這個ID需要在用戶註冊時同時創建。但是我不確定如何實現這種類型的邏輯。

+0

由於您使用的是設計,您只需傳入'current_user' – mrvncaragay

回答

0

我也是新來的鐵軌,但我的猜測是你的@ profile.save不成功,而@profile沒有一個ID。如果無法將配置文件保存到數據庫,保存將返回false。因此,添加如下內容:

if @profile.save 
    redirect_to @profile 
else 
    redirect_to 'new' 
end 

像你這樣做的更新。 您是否可能錯過了生成配置文件模型後運行數據庫遷移?

0

您需要在每個頁面請求上設置@profile時,user_signed_in?作爲profile_path路由助手在_navigation_links.html.erb取決於它。

因此,如果user_is_signed_in?,但在其執行ProfilesController#index行動profiles_page,那麼它會失敗,因爲你只爲[:show, :edit, :update, :destroy]設置@profile