Question

I'm pretty stumped about how to setup the friendly_id (4.0.0.beta12) gem to work properly with STI models.

Here is the model setup:

class Car < ActiveRecord::Base
  extend FriendlyId
  friendly_id :name, :use => :slugged
end

class Ford < Car
end

class Toyota < Car
end

If i try something like this:

Toyota.create!(name: "test")
Ford.create!(name: "test")

The resulting error is:

   (0.1ms)  BEGIN
  Ford Load (0.2ms)  SELECT `cars`.* FROM `cars` WHERE `cars`.`type` IN ('Ford') AND (`slug` = 'test' OR `slug` LIKE 'test--%') AND (id <> 7606) ORDER BY LENGTH(`slug`) DESC, `slug` DESC LIMIT 1
   (0.5ms)  UPDATE `cars` SET `slug` = 'test', `updated_at` = '2011-09-30 15:06:08' WHERE `cars`.`type` IN ('Ford') AND `cars`.`id` = 7606
   (0.1ms)  ROLLBACK
ActiveRecord::RecordNotUnique: Mysql2::Error: Duplicate entry 'test' for key 2: UPDATE `cars` SET `slug` = 'test', `updated_at` = '2011-09-30 15:06:08' WHERE `cars`.`type` IN ('Ford') AND `cars`.`id` = 7606

The problem is that friendly_id's select looks for the slug w/ type set to 'Ford' and comes up clean (as the slug 'test' already belongs to a record for type 'Toyota'). Assuming that no slug with the name 'test' exists, it then tries to save the record with the slug 'test' and everything goes to hell.

Any ideas?

Thank you!

Was it helpful?

OTHER TIPS

Maybe you could add a timestamp to the id, it would stop conflicts. Although it isn't the ideal solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top