FriendlyId not adding sequence and throwing Active

2019-07-23 00:24发布

The context is pretty simple, I have a Course model that extends from FriendlyId as follow:

extend FriendlyId
friendly_id :friendly_name, use: [:slugged, :history]

def friendly_name
  slugs = [self.type_name, self.name]
  slugs << self.city.name      if self.city
  slugs << self.structure.name if self.structure
  return slugs
end

And if I create a course with same type, name, city and structure I get the following error:

 !! #<ActiveRecord::RecordNotUnique: PG::Error: ERROR:  duplicate key value 
 violates unique constraint "index_courses_on_slug"
 DETAIL:  Key (slug)=(cours-sevillanas-copie-paris-12-la-trianera) already exists.

I don't understand why FriendlyId doesn't add a sequence number at the end of the slug... Any suggestion is welcomed.

I have tried to return a string instead of an array in the friendly_name method but the error persists.

Edit

Removing :history fixes the problem.

I'have also tried other branches (4.0-stable, 4.1.x) of FriendlyId but it doesn't fixes the problem.

1条回答
▲ chillily
2楼-- · 2019-07-23 01:03

I had the same problem with the :history features: it's because FriendlyId will use a separate table to store slugs, and will not check the existing slug column.

You can create a migration and re-save the whole table to generate missing slugs in the new slugs table.

For example:

def up
  MyModel.all.map(&:save)
end
查看更多
登录 后发表回答