如何将Friendly_Id与STI一起使用?
我对如何设置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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许你可以在 id 中添加一个时间戳,这样可以避免冲突。尽管这不是理想的解决方案。
Maybe you could add a timestamp to the id, it would stop conflicts. Although it isn't the ideal solution.
这篇文章解释了如何做到这一点:
http:// ruby.zigzo.com/2011/10/08/how-to-use-the-Friendly_id-gem-w-sti-models/
This post explains how to do it:
http://ruby.zigzo.com/2011/10/08/how-to-use-the-friendly_id-gem-w-sti-models/