How to use Friendly_Id w/ STI?
-
05-02-2021 - |
質問
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!
解決 2
This post explains how to do it: http://ruby.zigzo.com/2011/10/08/how-to-use-the-friendly_id-gem-w-sti-models/
他のヒント
Maybe you could add a timestamp to the id, it would stop conflicts. Although it isn't the ideal solution.
所属していません StackOverflow