注意这一切都未经测试,只是从文档中工作并阅读源代码。
您可以继承 FriendlyId::SlugGenerator 类,并重写 available? 方法以检查对立模型中的现有记录:
class CrossModelSlugGenerator << FriendlyId::SlugGenerator
def available?(slug)
if (@scope.class == "Item::ActiveRecord_Relation")
# Search for collections with this slug and return false if they exist.
elsif (@scope.class == "Collection::ActiveRecord_Relation")
# Search for items with the this slug and return false if they exist.
end
# Otherwise do a normal slug check
!@scope.exists_by_friendly_id?(slug)
end
end
您可以在此处查看 SlugGenerator 类的完整代码:
https://github.com/norman/friendly_id/blob/master/lib/friendly_id/slug_generator.rb
然后您必须告诉友好 ID 配置来使用该类。在config/initializers/friendly_id.rb中创建一个初始化器:
FriendlyId.defaults do |config|
config.slug_generator_class = "CrossModelSlugGenerator"
end
尝试一下,看看它是否适合您。再说一次,我还没有测试过它,但它似乎应该可以解决。
编辑 - 您可能需要像这样将类包装在 FriendlyId 模块中:
您可能需要在某处包含,可能在您的类定义中。另外,尝试将类包装到 FriendlyId 模块中,可能是这样的:
include "friendly_id"
module FriendlyId
class CrossModelSlugGenerator << SlugGenerator
...
end
end
通过此更改,您可能还需要在配置类名称中显式指定模块:
FriendlyId.defaults do |config|
config.slug_generator_class = "FriendlyId::CrossModelSlugGenerator"
end