0
votes

I have the friendly_id initializer to shorten the value if there is a duplicate value in the database.

# over writing the conflict slug
module FriendlyId
  module Slugged
    def resolve_friendly_id_conflict(candidates)
      candidates.first + friendly_id_config.sequence_separator + SecureRandom.hex(3)
    end
  end
end

Am using this in the Company Model as follows

extend FriendlyId
friendly_id :name, use: :slugged

Now if i leave the name blank and test the validation i am getting the following error

NoMethodError at /members

undefined method `+' for nil:NilClass


Company#resolve_friendly_id_conflict
config/initializers/friendly_id.rb, line 5
1
what about setting up a default string if the name is blank?margo

1 Answers

1
votes

The method you changed was able to handle if there were no candidates but your method doesn't.

See the original code...

[candidates.first, SecureRandom.uuid].compact....

The compact would drop the nil value.

I'd suggest you convert the first candidate to a string to handle that case.

candidates.first.to_s + friendly_id_config.sequence_separator + SecureRandom.hex(3)

Even better, you can stick to the original pattern... just replace the random field with your own.

def resolve_friendly_id_conflict(candidates)
  [candidates.first, SecureRandom.hex(3)].compact.join(friendly_id_config.sequence_separator)
end