Rails Friendly_id 字段空白时出错

Rails Friendly_id error when Field Blank

如果数据库中有重复值,我有 friendly_id 初始化程序来缩短值。

# 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

我在公司模型中使用它如下

extend FriendlyId
friendly_id :name, use: :slugged

现在,如果我将 name 留空并测试验证,我会收到以下错误

NoMethodError at /members

undefined method `+' for nil:NilClass


Company#resolve_friendly_id_conflict
config/initializers/friendly_id.rb, line 5

如果没有候选项,您更改的方法能够处理,但您的方法不能。

查看原代码...

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

契约会删除 nil 值。

我建议您将第一个候选项转换为字符串来处理这种情况。

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

更好的是,您可以坚持原来的模式...只需将随机字段替换为您自己的即可。

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