如何将Friendly_Id与STI一起使用?

发布于 2024-12-07 05:04:02 字数 1152 浏览 5 评论 0原文

我对如何设置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“test”已经属于类型“Toyota”的记录)。假设不存在名为“test”的 slug,则它会尝试使用 slug“test”保存记录,然后一切都会陷入困境。

有什么想法吗?

谢谢你!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

债姬 2024-12-14 05:04:02

也许你可以在 id 中添加一个时间戳,这样可以避免冲突。尽管这不是理想的解决方案。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文