3

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:"nousername@outlook.com", 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?

theStig
  • 612
  • 1
  • 13
  • 33

2 Answers2

3

With the help of @rich-peck I was able to figure out the solution to this problem after reading the source code of friendly_id. The root of the problem was that friendly_id uses a before_validation to set the slug.

In order to fix my problem, I had to set my model as following.

class User < ActiveRecord::Base
  extend FriendlyId 

  before_validation :set_default_username

  friendly_id :username, use: :slugged

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :omniauthable

  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
theStig
  • 612
  • 1
  • 13
  • 33
  • You did submit and accept an own answer even though your answer is mostly based on what @rich-peck suggested. You might consider accepting his answer and at least give him an up-vote if it did contribute to your solution. – Besi Jan 24 '19 at 21:12
1

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)?

Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147
  • thank you for that resource, as you might have noticed, I am fairly new to ruby. On another note, the slug is now being generated, but it's giving something completely useless. upon creation of a user where the username isn't set, the slug is -43f79fd3-57c2-4170-a677-769018bf92b1 – theStig Apr 21 '14 at 00:35
  • That's a UID. They're automatically generated in the event that the slug being created is a duplicate. – JasonMattingly Nov 21 '17 at 00:14