Raf
Raf

Reputation: 1083

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

I have the default friendly_id configuration in place in my project, which without comments looks like this:

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

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

And a model which has this configuration:

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

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

This is because the model is accessible through this route: /:id

My problem is that the model configuration overwrites the defaults in the config file. I can create the model with a name: 'new' and the slug will be set to 'new', while it will not work for other models.

I wasn't expecting this to be the default behaviour. Is there a way to have the defaults active while adding specific reserved words to a model?

Upvotes: 2

Views: 304

Answers (1)

Matt Brictson
Matt Brictson

Reputation: 11102

Each model that extends FriendlyId gets its own copy of the friendly_id configuration that you can manipulate. You can access (and modify) this configuration using friendly_id_config.

So you could concat your additional list of EXCLUDED_SLUG_VALUES onto the reserved_words, like this:

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

All of your models will continue to use the reserved words you specified in the default configuration, and MyModel will additionally reserve EXCLUDED_SLUG_VALUES.

Upvotes: 4

Related Questions