Rails - link_to用户#show

时间:2013-06-16 10:36:46

标签: ruby-on-rails ruby ruby-on-rails-3

在rails中,如何对当前用户的用户显示页面执行link_to。基本上我想要一个转到帐户页面的链接。

我试了但是我明白了。

  

路由错误没有路由匹配{: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

佣金路线

              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

2 个答案:

答案 0 :(得分:10)

只是

<%= link_to current_user.name, current_user%>

答案 1 :(得分:5)

当前的答案是最好的解决方案,但只是详细说明:导致代码出错的问题是您需要指定链接应链接到哪个用户。因此,您应该这样做,而不仅仅是user_path

= link_to "My account", user_path(current_user)

此快捷方式是(如@Muntasim的当前答案所示)

= link_to "My account", current_user