找不到Friendly_Id记录

时间:2013-12-03 23:10:34

标签: activerecord ruby-on-rails-4 friendly-id

使用带有Rails 4.0的friendly_id 5.0 stable

,我得到了一个未找到记录的异常

错误:

enter image description here

迁移:

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

控制器:

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

数据:

    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');

如果我将ID放入网址

,它就有效
 http://0.0.0.0:3000/users/10

但使用slug

时不起作用
 http://0.0.0.0:3000/users/tool

1 个答案:

答案 0 :(得分:6)

最快的解决方法是使用:readme中使用:finders addon来使用旧的4样式查找器。

然后您将通过“普通”find()方法进行友好ID访问。

示例:

friendly_id :foo, use: [:slugged, :finders] # you can now do MyClass.find('bar')