【问题标题】:Rails - link_to a user#showRails - 链接到用户#show
【发布时间】:2013-06-12 12:20:22
【问题描述】:

在 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

耙路

              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 "My account", user_path(params[:id])

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


【解决方案1】:

当前答案是最好的解决方案,但只是为了详细说明:导致代码错误的问题是您需要指定链接应链接到的用户。所以你应该这样做而不是user_path

= link_to "My account", user_path(current_user)

一个捷径是(如@Muntasim当前的回答所示)

= link_to "My account", current_user

【讨论】:

  • 很高兴看到有人用他们的答案提供解释。干杯@jokklan。
  • user_path(current_user) 是我想要的。没有current_user_path有什么原因吗?
  • @Nemo 因为模型被称为“用户”而不是“当前用户”。但是您可以自己创建它:resources :users, as: :current_users 您可以在这里阅读更多内容:guides.rubyonrails.org/…
【解决方案2】:

只是

<%= link_to current_user.name, current_user%>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多