Rails - link_to用户#显示页面

4
在Rails中,如何链接到当前用户的用户展示页面?基本上我想要一个链接,可以跳转到我的账户页面。我尝试过,但是出现了以下错误:
“路由错误,没有匹配的路由:{:action =>“show”,:controller =>“users”}” Routes.rb
LootApp::Application.routes.draw do
  get "password_resets/new"
  get "sessions/new"
  get "static_pages/home"
  get "static_pages/help"

  resources :sessions
  resources :password_resets
  resources :email_activations

  resources :users do
    collection do 
      get :accept_invitation
    end 
  end

  root to: 'static_pages#home'
  match "sign_up",      to: "users#new"
  match '/help',        to: 'static_pages#help'
  match '/log_in',      to: 'sessions#new'
  match '/log_out',     to: 'sessions#destroy'

Application.html.haml

      - if current_user 
        = link_to "log out", log_out_path
        - if current_user.admin?
          # your admin
        - else
          = link_to "My account", user_path
      - else
        = link_to "log in", log_in_path

用户控制器

class UsersController < ApplicationController
  before_filter :admin_and_user, only: [:destory, :edit, :show]

  def show
    @user = User.find(params[:id]) 
  end

rake routes

              users GET    /users(.:format)                      users#index
                    POST   /users(.:format)                      users#create
           new_user GET    /users/new(.:format)                  users#new
          edit_user GET    /users/:id/edit(.:format)             users#edit
               user GET    /users/:id(.:format)                  users#show
                    PUT    /users/:id(.:format)                  users#update
                    DELETE /users/:id(.:format)                  users#destroy

我尝试使用link_to "我的账户", user_path(params[:id])。 - Alain Goldman
2个回答

11
<%= link_to current_user.name, current_user%>

5

目前的回答是最佳解决方案,但是需要详细说明:您的代码出现错误的原因是您需要指定链接应链接到哪个用户。所以,不要仅使用 user_path,而应该像这样:

= link_to "My account", user_path(current_user)

这个的快捷方式是(如当前答案@Muntasim所示)
= link_to "My account", current_user

很高兴看到有人在回答中提供解释。感谢@jokklan。 - thomasfedb
user_path(current_user) 是我正在寻找的。有没有什么原因没有 current_user_path - Nemo
@Nemo,因为模型被称为“User”,而不是“CurrentUser”。但是你可以自己创建它:resources :users, as: :current_users。你可以在这里阅读更多信息:http://guides.rubyonrails.org/routing.html#overriding-the-named-helpers - jokklan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接