简体   繁体   中英

`Couldn't find User without an ID` with Friendly_ID gem

I am creating User Profiles with vanity URLs that use the username. The actual profile page works well, however I have my root page as the profile page if the user is signed in. If they are redirected to root then they get the error Couldn't find User without an ID and shows this code as the error pointing to the @user line...

class ProfilesController < ApplicationController

    def show
        @current_user = current_user
        @user = User.friendly.find(params[:id])
        @username = "@" + @user.username
        @posting = Posting.new
    end

end

Here is my routes file as well...

devise_for :users
  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".
  get "profiles/show"

  devise_scope :user do
    get '/register', to: 'devise/registrations#new', as: :register
    get '/login', to: 'devise/sessions#new', as: :login
    get '/logout', to: 'devise/sessions#destroy', as: :logout
    get '/edit', to: 'devise/registrations#edit', as: :edit
  end

  authenticated :user do
    devise_scope :user do
      root to: "profiles#show", :as => "authenticated"
    end
  end

  unauthenticated do
    devise_scope :user do
      root to: "devise/sessions#new", :as => "unauthenticated"
    end
  end

  get '/:id' => 'profiles#show', as: :profile

This is not the problem with friendly id gem. The problem is that you are redirecting to a show method without supplying id, hence params[:id] is nil.

You can go around this by changing your show method:

def show
  @current_user = current_user # why do you need this?
  @user = params[:id] ? User.friendly.find(params[:id]) : current_user
  @username = "@" + @user.username
  @posting = Posting.new
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM