有没有办法让 FriendlyId gem 中的模型的 :reserved_words 选项不覆盖 Rails 默认值?

Is there a way that the :reserved_words option for models in FriendlyId gem does not overwrite the Rails defaults?

我的项目中有默认的 friendly_id 配置,没有注释看起来像这样:

FriendlyId.defaults do |config|
  config.use :reserved

  config.reserved_words = %w(new edit index session login logout users admin stylesheets assets javascripts images)
end

以及具有此配置的模型:

EXCLUDED_SLUG_VALUES = %w(users articles authors topics admin your all)

friendly_id :name, use: :slugged, reserved_words: EXCLUDED_SLUG_VALUES

这是因为可以通过以下路径访问该模型:/:id

我的问题是模型配置覆盖了配置文件中的默认值。我可以使用 name: 'new' 创建模型,并且 slug 将设置为 'new',但它不适用于其他模型。

我没想到这是默认行为。有没有办法在向模型添加特定保留字时激活默认值?

每个扩展 FriendlyId 的模型都有自己的 friendly_id 配置副本,您可以对其进行操作。您可以使用 friendly_id_config.

访问(和修改)此配置

所以您可以 concat 您的 EXCLUDED_SLUG_VALUES 附加列表到 reserved_words,像这样:

class MyModel < ActiveRecord::Base
  extend FriendlyId
  EXCLUDED_SLUG_VALUES = %w(users articles authors topics admin your all)
  friendly_id_config.reserved_words.concat(EXCLUDED_SLUG_VALUES)
  friendly_id :name, use: :slugged
end

您的所有模型将继续使用您在默认配置中指定的保留字,并且MyModel将额外保留EXCLUDED_SLUG_VALUES