rails4 add friendly_id有错误的未定义方法`slug'for

时间:2018-05-02 11:58:23

标签: ruby-on-rails friendly-id

我使用了rails4.2.8,ruby2.5.0,'friendly_id','〜> 5.1.0'

当我将friendly_id加载到Gemfile时,

首先:bundle
第二:rake db:migrate
第三:在models/user.rb添加

extend FriendlyId
  friendly_id :name, use: :slugged
controllers/user_controller.rb中的

更改如下:

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

然后我rails s并创建新用户,它显示错误:

NoMethodError in UsersController#create
undefined method `slug' for #<User:0x00007f89fb2d7508>

def create
    @user = User.new(user_params) 
    if @user.save
      log_in @user
      flash[:success] = "signup success~"
      redirect_to @user

我在stackoverflow中搜索过这个错误,有人说改变models/user.rb

 extend FriendlyId
  friendly_id :name, :use => [:slugged, :finders]

我试过这个答案,但它也显示错误:

NoMethodError in UsersController#create
undefined method `slug' for #<User:0x00007f89fb2d7508>

我该如何解决这个问题?非常感谢你的帮助~~~

1 个答案:

答案 0 :(得分:5)

您需要通过迁移向您的users表添加一个slug列。创建新迁移: rails g migration addSlugToUsers

然后添加:

add_column :users, :slug, :string 
add_index :users, :slug, unique: true

db/migrate/xxxx.add_slug_to_users.rb

并运行:rails db:migrate