加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails4 Friendly_id独特的Slug格式

发布时间:2020-12-16 19:01:39 所属栏目:百科 来源:网络整理
导读:我正在使用friendly_id gem来阻止我的模型.因为当我输入相同的数据来检查时,slug必须是唯一的,我会在slug中附加一个长的哈希值. Explore explore Explore explore-7a8411ac-5af5-41a3-ab08-d32387679f2b 有没有办法告诉friendly_id提供更好的格式化slug,如ex
我正在使用friendly_id gem来阻止我的模型.因为当我输入相同的数据来检查时,slug必须是唯一的,我会在slug中附加一个长的哈希值.
Explore     explore 
Explore     explore-7a8411ac-5af5-41a3-ab08-d32387679f2b

有没有办法告诉friendly_id提供更好的格式化slug,如explore-1和explore-2

版本:friendly_id 5.0.4

解决方法

同意,这似乎是非常粗暴的行为.

如果你看一下friendly_id / slugged.rb的代码,有2个函数处理冲突解决逻辑:

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

所以,这个想法只是为了修补它.我看到2个选项:

>只需修补resolve_friendly_id_conflict,添加随机后缀.
>改变两种方法的逻辑,试图尝试所有候选者,直到slug_generator.generate(候选者)返回非空的东西.如果所有候选人都给nil然后回退到resolve_friendly_id_conflict方法.
使用这种技术,你可以使用slug候选者在slug不唯一时附加模型的id.

理想情况下,如果gem的作者添加了一个配置选项来处理独特的slugs解析(方法符号或proc将生成器和候选者作为params)或者只是检查模型是否响应某种方法,那将是很好的.

此外,在一些使用案例中,根本不需要独特的段塞分辨率.例如,如果我们只想依靠validates_uniqueness_of:slug或候选者的唯一性验证.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读