ruby - Prevent race-conditions in slug generation with friendly-id and rails -


in used application running problems unique database constraint on slug column.

class profile < activerecord::base   extend friendlyid    friendly_id :slug_candidates, use: :slugged end 

a method in profile calls:

  save! if valid? 

and results in mysql2::error: duplicate entry 'evert-159226' key 'index_profiles_on_slug'

how can prevent this?

welcome stack overflow! problem you're facing rails-side validation doesn't guarantee uniqueness when perform save operation. there 2 way solve that

  1. issue table-level lock avoid other records being inserted or updated. influence performance quite heavily
  2. save object without slug first , keep updating atomic operations until you're successful.

i can provide wth example code both if wish.


Comments