Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

friendly_id slug is not generating on create

I have an active record callback on my user model to generate a username if the user didn't specify a username. This would occur when the user would register via Google, Facebook, or any other third party.

class User < ActiveRecord::Base
  extend FriendlyId
  friendly_id :username, use: :slugged

  before_validation :set_default_username 

  private

    def set_default_username
      self.username ||= "user#{User.last.id+1}"
    end

end

The problem is, in my seeds file, i noticed for one of my users, the slug was not being created, specifically on this case:

User.create(email:"[email protected]", password: "password")

While the username is being created due to set_default_username, the slug is not being created. Is there any way to fix this?

like image 299
theStig Avatar asked Nov 26 '25 07:11

theStig


1 Answers

Perhaps it's a friendly_id issue:

Class User < ActiveRecord::Base
  extend FriendlyId
  friendly_id :username, use: :slugged

  before_save :set_default_username 

  private

    def set_default_username
      self.username ||= "user#{User.maximum(:id).next}"
    end

    def should_generate_new_friendly_id?
      slug.blank? || username_changed?
    end

end

A resource for you: Ruby on Rails: How to get ActiveRecord to show the next id (last + 1)?

like image 156
Richard Peck Avatar answered Nov 28 '25 21:11

Richard Peck