4
votes

In rails how do I do a link_to a user show page of the current user. Basically i want a link that go to a account page.

I tried it but i get this.

Routing Error No route matches {: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

Users controller

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
2
i tried = link_to "My account", user_path(params[:id])Alain Goldman

2 Answers

11
votes

just

<%= link_to current_user.name, current_user%>
5
votes

The current answer is the best solution, but just to elaborate: The problem that was causing an error in your code was that you needed to specify which user the link should link to. So instead of just user_path should you do like this:

= link_to "My account", user_path(current_user)

A shortcut for this is (as shown in the current answer by @Muntasim)

= link_to "My account", current_user