2016-01-20 41 views
1

我通過做一個項目的Web應用程序, 學習Ruby on Rails的,每當我去得到錯誤找不到用戶與「ID」 = ID

<%= link_to 'My Profile', user_path(:id) %>
錯誤
Couldn't find User with 'id'=id" is shown...and url is " http://localhost:3000/users/id
如果我上面的鏈接轉換爲
<%= link_to 'My Profile', user_path %>
,它的工作原理,但現在除了用戶的顯示頁面中的所有其他網頁給出錯誤
No route matches {:action=>"show", :controller=>"users"} missing required keys: [:id]
....我似乎無法找到任何地方的任何解決方案...

這裏是我的CONFIGS:
耙路線

     Prefix Verb URI Pattern      Controller#Action 
        root GET /        static#landing 
     new_user_session GET /users/sign_in(.:format)   devise/sessions#new 
      user_session POST /users/sign_in(.:format)   devise/sessions#create 
    destroy_user_session DELETE /users/sign_out(.:format)   devise/sessions#destroy 
      user_password POST /users/password(.:format)   devise/passwords#create 
     new_user_password GET /users/password/new(.:format)  devise/passwords#new 
     edit_user_password GET /users/password/edit(.:format) devise/passwords#edit 
         PATCH /users/password(.:format)   devise/passwords#update 
         PUT /users/password(.:format)   devise/passwords#update 
cancel_user_registration GET /users/cancel(.:format)   devise/registrations#cancel 
     user_registration POST /users(.:format)     devise/registrations#create 
    new_user_registration GET /users/sign_up(.:format)   devise/registrations#new 
    edit_user_registration GET /users/edit(.:format)    devise/registrations#edit 
         PATCH /users(.:format)     devise/registrations#update 
         PUT /users(.:format)     devise/registrations#update 
         DELETE /users(.:format)     devise/registrations#destroy 
     user_confirmation POST /users/confirmation(.:format)  devise/confirmations#create 
    new_user_confirmation GET /users/confirmation/new(.:format) devise/confirmations#new 
         GET /users/confirmation(.:format)  devise/confirmations#show 
        user GET /users/:id(.:format)    users#show

_header.html.erb <%= link_to 'My Profile', user_path %>

users_controller.rb class UsersController < ApplicationController def show @user = User.find(params[:id]) end end

的routes.rb Rails.application.routes.draw do root 'static#landing' devise_for :users resources :users, :only => [:show]

回答

2

您需要將用戶的ID user_path,不是符號:id - 像

<%= link_to 'My Profile', user_path(@current_user.id) %> 

,如果你要鏈接到用戶在一個實例變量 - 或者因爲使用的是設計,它提供了你可能會想

<%= link_to 'My Profile', user_path(current_user.id) %> 
+0

感謝男人......工作! –

0

我想的第一件事錯CURRENT_USER助手是這樣的:

<%= link_to 'My Profile', user_path(:id) %> 

您使用的是符號,不是一個變量

<%= link_to 'My Profile', user_path(@id) %> 

將有一個實際的變量,假設你已經在你的controlle設置@id河

但是,通常情況下,您不會爲路徑中的用戶設置ID--這是某人只需手動更改號碼並查看其他人的配方。假設你設置了一個名爲user_id的會話變量,那麼你應該做一些添加收集路由的操作 - 因此不會發送id。

resources :users do 
    get :show_profile, on: :collection 
end 

,它會給你你show_profile行動的路徑,調用

link_to 'My Profile', show_profile_user_path 

然後在你的控制器做你的用戶從會話查找 - 所以像:

@user = User.find_by id: session[:user_id] 

我不知道設備如何處理,但請不要相信用戶不會擺弄你的參數!