2016-03-01 53 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