0

我正在使用设计,在我的显示视图中我有:

<%= link_to "Profile", current_user %>

访问视图时,出现错误:

No route matches {:controller=>"users", :action=>"show"} missing required keys: [:id]

我的表演方法(由一位非常有帮助的 SO 成员建议):

  def show
    if params[:id]
      if current_user
        @user = current_user
      else
        flash[:notice] = "This page is not available"
        redirect_to root_path
      end
    else
      @user = current_user
    end
  end

我的路线:

  devise_for :users, :path => '', :path_names => { :sign_in => 'login', :sign_out => 'logout',
                                      :password => 'password', :confirmation => 'verification',
                                      :unlock => 'unblock', :registration => 'signup',
                                      :sign_up => 'new' }

    get   'login' => 'users/login'

  devise_scope :user do
    get   'login',          to: 'devise/sessions#new'
    get   'users/login',    to: 'devise/sessions#new'
    get   'logout',         to: 'devise/sessions#destroy'
    get   'signup',         to: 'devise/registrations#new'
    get   'password',       to: 'devise/passwords#new'
    match 'users/secret',   to: "devise/passwords#create",      via: :post
    match 'sessions/user',  to: 'devise/sessions#create',       via: :post
    match 'users/signup',   to: 'devise/registrations#create',  via: :post
    match 'users/signup',   to: 'devise/registrations#create',  via: :post
  end

  #resources :users
  #resources :users
resources :sessions

# Authenticated Users:
authenticated :user do
  root to: "users#show", as: :authenticated_root
end 

# Non-Authenticated Users
root to: 'site#index'

get '', to: 'users#show', as: 'user'
get 'edit', to: 'users#edit', as: 'user/edit'

任何想法为什么 current_user 助手返回错误?

4

1 回答 1

2

当您以未经身份验证的访问者身份访问视图时,您会收到此错误,因为 current_user 为 nil 并且没有与 user_path(nil) 对应的路由。最简单的解决方法(虽然不一定是我推荐的方法)是在 config/routes.rb 中更改这一行:

get '', to: 'users#show', as: 'user'

get 'profile', to: 'users#show', as: 'profile'

然后将视图更新为

<%= link_to "Profile", (current_user ? user_path(current_user) : profile_path) %>

一个更复杂的(但在我看来架构上更优越的选择)是将所有 no-id 逻辑从您的用户控制器中提取到具有如下索引方法的配置文件控制器中:

class ProfileController
  before_filter :check_authentication, only: [:index]

  def check_authentication
    unless current_user
      flash[:notice] = "This page is not available"
      redirect_to root_path
    end
  end

  def index
    @user = current_user
    render 'users/show'
  end
end

然后您将添加匹配的路线并更新您的链接以指向此操作。

您编写的用户 show 方法基本上忽略了 params[:id],这意味着它实际上不是 show 方法。无论传入哪个 id,它总是显示 current_user 的页面。这个 ProfileController 反映了这一点。

然后 users show 方法再次变成了一个简单的 show 方法,它只是通过 id 查找,这是它应该做的。

于 2013-11-05T17:19:33.557 回答