gpt4 book ai didi

ruby-on-rails - 使用Rails 5,如何使FriendlyId附加-"count+1"来重复slugs而不是UUID?

转载 作者:行者123 更新时间:2023-12-03 09:01:27 24 4
gpt4 key购买 nike

显然,FriendlyId 已更改了之前将数字序列附加到重复 slugs 的默认方法(这正是我想要的),现在使用 UUID:

Previous versions of FriendlyId appended a numeric sequence to make slugs unique, but this was removed to simplify using FriendlyId in concurrent code.

我目前对此功能不感兴趣,并且更喜欢使用原始方法来生成更清晰的 URL。我发现了一个类似的问题,其中 someone provided下面的代码覆盖了FriendlyId normalize_Friendly_id方法来获得我想要的功能,但是使用它会导致错误(参数数量错误(给定1,预期0)):

def normalize_friendly_id
count = self.count "name = #{name}"
super + "-" + count if name > 0
end

我试图将其“转换”为FriendlyId“候选人”,但我真的不知道我在做什么,并且以下内容不起作用。关于如何调整 name_candidate 方法来产生我想要的结果有什么想法吗?

class Folder < ApplicationRecord
extend FriendlyId
friendly_id :name_candidates, use: [ :slugged, :scoped ], scope: :account_id

has_ancestry

belongs_to :account
has_many :notes, dependent: :destroy

validates :name, presence: true

# # https://stackoverflow.com/a/25380607/523051
# # overrride friendlyId to append -number to duplicate folders instead of uuid's
# def normalize_friendly_id
# count = self.count "name = #{name}"
# super + "-" + count if name > 0
# end

def name_candidates
append_number = self.count "name = #{name}" if name > 0
[
:name,
:name, append_number
]
end
end

注意,我正在利用FriendlyId 的:scoped 功能,因此现有文件夹名称的检查应正确限定为:account_id

最佳答案

Friendly_id 5 现在有一个 slug_candidates,可让您自定义 slug。

因此,要生成连续的 slug,您可以这样做:

friendly_id :slug_candidates, use: :slugged

def slug_candidates
[:name, :name_and_sequence]
end

def name_and_sequence
slug = normalize_friendly_id(name)
sequence = Model.where("slug like '#{slug}--%'").count + 2
"#{slug}--#{sequence}"
end

这将在以下问题中讨论: https://github.com/norman/friendly_id/issues/480

According to the author, sequential slugs are bad for performance .

关于ruby-on-rails - 使用Rails 5,如何使FriendlyId附加-"count+1"来重复slugs而不是UUID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49844078/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com