我正在使用Friendly_id gem 来攻击我的模型。由于当我输入相同的数据来检查时,slug 必须是唯一的,因此我会在 slug 中附加一个长哈希值。
Explore explore
Explore explore-7a8411ac-5af5-41a3-ab08-d32387679f2b
有没有办法告诉Friendly_id提供更好格式的slugs,例如explore-1
and explore-2
Version: friendly_id 5.0.4
同意,这似乎是相当粗鲁的行为。
如果你看一下代码friendly_id/slugged.rb
,有两个函数处理冲突解决逻辑:
def resolve_friendly_id_conflict(candidates)
candidates.first + friendly_id_config.sequence_separator + SecureRandom.uuid
end
# Sets the slug.
def set_slug(normalized_slug = nil)
if should_generate_new_friendly_id?
candidates = FriendlyId::Candidates.new(self, normalized_slug || send(friendly_id_config.base))
slug = slug_generator.generate(candidates) || resolve_friendly_id_conflict(candidates)
send "#{friendly_id_config.slug_column}=", slug
end
end
所以,我们的想法只是修补它。我看到两个选项:
只需打补丁resolve_friendly_id_conflict
,添加您的随机后缀。
改变两种方法的逻辑,尝试所有候选方法,直到slug_generator.generate(candidates)
返回不为空的东西。如果所有候选人都给出nil
然后回退到resolve_friendly_id_conflict
方法。
使用这种技术,您可以使用 slug 候选者来附加模型的id
当 slug 不唯一时。
理想情况下,如果 gem 的作者添加了一个配置选项来处理独特的 slugs 解析(方法符号或 proc 将生成器和候选者作为参数)或者只是检查模型是否响应某种方法,那就太好了。
此外,在某些用例中,根本不需要独特的段解析。例如,如果我们只想依赖validates_uniqueness_of :slug
或候选者的唯一性验证。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)