gpt4 book ai didi

ruby-on-rails - friendly_id gem with rails,转换为 SEO 友好的 url

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:33:07 24 4
gpt4 key购买 nike

我使用的是 friendly_id 和 rails 3.2。我正在尝试将产品表转换为具有干净的网址。我在使用新的 slug 列时没有遇到任何问题,并且 url 生成的很好,就像

example.com/products/new-friendly-url

我遇到的问题是,我仍然想保留事件记录中的唯一 ID,或其他一些唯一标识符。原因是,许多产品可能具有相同的友好标题。如果我有一个具有完全相同标题的产品,则当前行为会生成一个带有一些唯一标识的 slug,例如:

example.com/products/new-friendly-url--2

所以 friendly_id 正在生成独特的 slug,但我只是想更改格式,但不确定在哪里/如何做。

有没有一种方法可以删除多余的 --,而只添加一个 friendly_id 添加的“-”?

这是我的模型

       class Product < ActiveRecord::Base
extend FriendlyId
friendly_id :title, :use => :slugged

attr_accessible :description, :image, :posted_by, :title, :url,
:price

validates_format_of :price, :with => /^[0-9]+$/

belongs_to :user
has_many :comments

最佳答案

您可以在 friendly-id 配置中更改序列分隔符。

class Product < ActiveRecord::Base
extend FriendlyId
friendly_id :title do |config|
config.use :slugged
config.sequence_separator = ":"
end
end

不建议将分隔符更改为“-”的操作。文件说:

The string used to separate a slug base from a numeric sequence.

By default, -- is used to separate the slug from the sequence. FriendlyId uses two dashes to distinguish sequences from slugs with numbers in their name.

You can change the default separator by setting the sequence_separator configuration option.

For obvious reasons, you should avoid setting it to “-” unless you're sure you will never want to have a friendly id with a number in it.

http://norman.github.io/friendly_id/4.0/FriendlyId/Slugged/Configuration.html#sequence_separator-instance_method

如果你可以使用 Rails 4,你可以将 friendly-id 升级到 5.0,它会自动解决这个问题。

关于ruby-on-rails - friendly_id gem with rails,转换为 SEO 友好的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18649979/

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