1

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~~~

4
  • you need to add the column :slug to your user table
    – Sovalina
    Commented May 2, 2018 at 12:19
  • @sovalina Thanks for your help ,how should I add the columm :slug to my user table ? could you show me the codes? Thanks so much~~
    – SylorHuang
    Commented May 2, 2018 at 12:33
  • 1
    check @a3y3 answer :)
    – Sovalina
    Commented May 2, 2018 at 12:35
  • OK,thank you so much also...
    – SylorHuang
    Commented May 2, 2018 at 12:37

1 Answer 1

5

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

1
  • Hi @a3y3 , thanks for your help , it works good. And then , could you help me to answer other question if you have time? The url is :https://stackoverflow.com/questions/50114586/rails4-change-default-url-xxx-com-new-page-to-xxx-com-new-page-username, I couldn't solve this questions either, for I'm the beginner for rails.
    – SylorHuang
    Commented May 2, 2018 at 13:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.