【问题标题】:Rails Friendly_id error when Field Blank字段空白时出现 Rails Friendly_id 错误
【发布时间】:2016-04-13 07:32:53
【问题描述】:

如果数据库中有重复值,我有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

【问题讨论】:

  • 如果名称为空,如何设置默认字符串?

标签: ruby-on-rails ruby-on-rails-4 friendly-id


【解决方案1】:

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

查看原代码...

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    • 2011-02-15
    相关资源
    最近更新 更多