1

Inside my model, I have the following:

friendly_id :id_and_title, use: [:slugged, :finders]

...

def id_and_title
    "#{self.id}-#{self.title}"[0,100]
end

However, when creating a new record, the ID isn't being used on the slug field.

What I'm currently doing is:

after_save :regenerate_slug

...

def regenerate_slug
    self.slug = nil
    self.save
end

and I'm wondering if there is any other way of doing this?

Oscar Mederos
  • 29,016
  • 22
  • 84
  • 124

1 Answers1

0

So the problem is that friendly_id does not have access to "id" until after the record is created. The issue here is the after_save causes infinite recurrence, like Michal said, since it calls save.

You should use an after_create instead. You only need to do this once. In all subsequent updates to the record the id should be available for friendly_id to pick up.

@user3062913 has the solution for it here: Rails4 Friendly_id Unique Slug Formatting

Community
  • 1
  • 1
Han Chen
  • 63
  • 4