Search code examples
ruby-on-railsactiverecordslug

Generating a slug after Active Record object creation in rails


I'm trying to generate a unique slug for an object after the object is created using the after_commit callback.

after_commit :create_slug, on: :create

def create_slug
    self.slug = generate_slug
    self.save
end

When I try to save the object I get a "stack level too deep" error. I'm assuming because I'm saving the object and it's called the after_commit callback again and again.

What's the best way to generate and save the unique slug in this situation?


Solution

  • I recommend using the after_validation callback on create rather than the after_commit. You will be calling multiple transactions, which is not the intention of this callback. What I would do is this:

    after_validation(on: :create) do
      self.slug = generate_slug
    end
    

    Also make sure there are no save actions going on inside the generate_slug. That method should simply be returning a value to insert into the slug attribute.