如何使用带有STI的Friendly_Id?

时间:2011-09-30 19:01:42

标签: ruby-on-rails ruby ruby-on-rails-3 rubygems friendly-id

我对如何设置friendly_id(4.0.0.beta12)gem以便与STI模型正常工作感到非常难过。

以下是模型设置:

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

class Ford < Car
end

class Toyota < Car
end

如果我尝试这样的事情:

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

产生的错误是:

   (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

问题是,friendly_id的选择会查找设置为'Ford'并且类型为slug的slug(因为slu''test'已经属于'Toyota'类型的记录)。假设没有名为'test'的slug存在,那么它会尝试使用slug'test'保存记录,一切都会变成地狱。

有什么想法吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

也许你可以为id添加一个时间戳,它会阻止冲突。虽然它不是理想的解决方案。

答案 1 :(得分:0)