Search code examples
ruby-on-railsfriendly-id

rails4 add friendly_id has wrong undefined method `slug' for


I used rails4.2.8, ruby2.5.0, 'friendly_id', '~> 5.1.0'

when I gem the friendly_id to the Gemfile,

first: bundle
second: rake db:migrate
third: in models/user.rb add

extend FriendlyId
  friendly_id :name, use: :slugged

in controllers/user_controller.rb change as follows:

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

and then I rails s and creat new users , it display a wrong:

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

I had search this wrong in stackoverflow , someone said change models/user.rb as

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

I had try this answer ,but it also displays the wrong as this:

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

How can I to solve this questions? thanks for your help so much~~~


Solution

  • You need to add a slug column to your users table through a migration. Create a new migration: rails g migration addSlugToUsers

    then add:

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

    to db/migrate/xxxx.add_slug_to_users.rb

    And run: rails db:migrate