【问题标题】:Devise + associated Profile model - show profile page returning error设计 + 关联的配置文件模型 - 显示配置文件页面返回错误
【发布时间】:2013-11-20 10:14:08
【问题描述】:

带有链接的静态页面

<h1>Dashboard</h1>
<%= link_to 'Dashboard', :action => :dashboard %> |
<%= link_to 'Ask for help', :controller => :tasks, :action => :new %> |
<%= link_to 'Profile', profile_path %>| #relevant line

配置文件控制器

class ProfilesController < ApplicationController
    def new
        @profile = Profile.new
    end

    def create
         @profile = Profile.new(params[:profile])
         @profile.user_id = current_user.id
         if @profile.save
             redirect_to static_pages_dashboard_path
         end
    end

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

    def show
        @profile = Profile.current_user
    end
end

routes.rb

 Test::Application.routes.draw do
      get "welcome/index"
      get "static_pages/home"
      get "static_pages/dashboard"
      get "tasks/index"

      root "static_pages#home"
      devise_for :users 
      resources :tasks
      resources :profiles
 end

我正在尝试制作一个单独的模型/控制器来处理用户的个人信息,称为profile

尝试从仪表板视图链接到 show 操作/视图会导致错误:

StaticPages#dashboard 中的 ActionController::UrlGenerationError
没有路由匹配 {:controller=>"profiles", :action=>"show"} 缺少必需的键:[:id]


我该如何解决这个问题?
谢谢!

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    您应该传递配置文件 ID 以使配置文件显示 url 生成成为可能(否则,Rails 不知道您要链接到哪个配置文件):

    <%= link_to 'Profile', profile_path(current_user.profile) %>
    

    当然,您需要确保已设置关联并且用户始终拥有关联的个人资料。或者,您可以在呈现链接之前检查配置文件是否存在,如下所示:

    <%= link_to 'Profile', profile_path(current_user.profile) if current_user.profile %>
    

    【讨论】:

    • 您好,我按照您的建议进行了尝试,但仍然出现错误 - No route matches {:id=&gt;nil} missing required keys: [:id]@marek
    • @jenkhai 这是因为您的 current_user 没有关联的个人资料。请查看我编辑的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    相关资源
    最近更新 更多