Question

I get a record not found exception using friendly_id 5.0 stable with Rails 4.0

Error:

enter image description here

Migration:

class AddSlugToUsers < ActiveRecord::Migration
    def change
       add_column :users, :slug, :string
       add_index :users, :slug
    end
end

Controller:

class UsersController < ApplicationController
  load_and_authorize_resource
  before_filter :authenticate_user!

  def index
    authorize! :index, @user, :message => 'Not authorized as an administrator.'
    @users = User.all
  end

  def show
    #@user = User.find(params[:id])
    @user = User.friendly.find(params[:id])
  end

  def update
    authorize! :update, @user, :message => 'Not authorized as an administrator.'
    @user = User.find(params[:id])
    if @user.update_attributes(params[:user], :as => :admin)
      redirect_to users_path, :notice => "User updated."
    else
      redirect_to users_path, :alert => "Unable to update user."
    end
  end


  def destroy
    authorize! :destroy, @user, :message => 'Not authorized as an administrator.'
    user = User.find(params[:id])
    unless user == current_user
      user.destroy
      redirect_to users_path, :notice => "User deleted."
    else
      redirect_to users_path, :notice => "Can't delete yourself."
    end
  end

end

The Data:

    INSERT INTO 
users(id,email,encrypted_password,reset_password_token,reset_password_sent_at,remember_created_at,
sign_in_count,current_sign_in_at,last_sign_in_at,current_sign_in_ip,last_sign_in_ip,
created_at,updated_at,first_name,last_name,alias,bio,slug) 
VALUES 
(10,'me1@example.com','$2a$10$MYHASG','',null,null,0,null,null,'','',
Invalid Date,Invalid Date,'greek','god','tool','','tool');

It works if I put the ID into the url

 http://0.0.0.0:3000/users/10

but does not work when using the slug

 http://0.0.0.0:3000/users/tool
Was it helpful?

Solution

The quickest fix is to use the old 4-style finders as described in the readme by using the :finders addon.

Then you'll have friendly-id access via the "normal" find() method.

Example:

friendly_id :foo, use: [:slugged, :finders] # you can now do MyClass.find('bar')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top