【问题标题】:Exclude specific words from being saved to database从保存到数据库中排除特定单词
【发布时间】:2015-03-31 22:11:45
【问题描述】:

我的照片模型有一个标题属性。我不希望用户添加诸如...图片、打印、照片、图像、照片、图片之类的词

我有这个验证,但在尝试创建/更新标题时似乎没有得到它

验证:title, exclude: { inside: %w(picture, Print, photo, image, photo, pic),

我也用 :in 试过了

验证 :title, exclude: { in: %w(picture, Print, photo, image, photo, pic)

关于为什么将像“芝加哥天际线照片”这样的标题保存到数据库的任何想法?

【问题讨论】:

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


    【解决方案1】:

    排除将捕获“照片”,但不会捕获“天际线照片”或“芝加哥天际线照片”......它仅检查整个属性。

    使用自定义验证会更好。

    validate :reject_if_includes_image_words
    
    def reject_if_includes_image_words
      title.split(' ').each do |word|
        if %w(picture print photo image photograph pic).include? word.downcase
          errors.add(:title, "can't include the word '#{word}'")
          break
        end
      end
    end
    

    编辑

    处理标点或数字的情况并包含@pdobb的出色建议...

    IMAGE_WORDS = %w(picture print photo image photograph pic)
    
    validate :reject_if_includes_image_words
    
    def reject_if_includes_image_words
      used_image_words = title.gsub(/[^A-Za-z\s]/,'').split & IMAGE_WORDS
      errors.add(:title, "can't use '#{used_image_words.join('\', \'')}'") if used_image_words.any?
    end
    

    【讨论】:

    • 可能会节省一些滴答声以使用数组交集。然后,Plus 可以在错误消息中包含所有无效单词:invalid_words = %w(picture print photo image photograph pic) & "asdf picture and pic".split 然后errors.add(:title, "can't include the word(s): #{invalid_words.join(', ')}") if invalid_words.any?。将图像单词列表移动到常量中也是理想的。
    • 好建议@pdobb
    • 如何修改该函数以不包含数字或括号?
    • 嗨,看看编辑,它现在忽略了数字或标点符号,并结合了@pdobb 提出的好建议。干杯
    猜你喜欢
    • 1970-01-01
    • 2018-08-24
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多