current_user helper在视图中返回错误

时间:2013-11-05 16:40:33

标签: ruby-on-rails devise routes ruby-on-rails-4

我正在使用Devise,在我的节目视图中我有:

<%= link_to "Profile", current_user %>

访问视图时,出现错误:

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

我的show方法(由非常有帮助的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帮助器返回错误的任何想法?

1 个答案:

答案 0 :(得分: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) %>

更复杂(但在我看来,架构优越的选项)是将用户控制器中的所有无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

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

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

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