1

我很困惑如何设置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 的选择查找类型设置为“福特”的slug 并干净利落(因为slug 'test' 已经属于类型'Toyota' 的记录)。假设不存在名为 'test' 的 slug,然后它会尝试使用 slug 'test' 保存记录,一切都将陷入困境。

有任何想法吗?

谢谢!

4

2 回答 2

0

也许您可以在 id 中添加时间戳,它会停止冲突。虽然这不是理想的解决方案。

于 2011-10-07T13:30:57.160 回答
0

这篇文章解释了如何做到这一点: http ://ruby.zigzo.com/2011/10/08/how-to-use-the-friendly_id-gem-w-sti-models/

于 2011-10-08T20:13:05.767 回答