被保存到数据库
问题描述:
排除特定的词我有我的照片模型title属性。我不希望用户添加词语,如...图片,打印,照片,图像,照片,PIC被保存到数据库
我在这个地方验证,但它似乎并没有试图创建时要捡起来/更新标题
验证:标题,排除:{内:%重量(图象,打印,照片,图像,照片,图),
我尝试了:在以及
验证:标题,排除:{在:%(重量)(图象,打印,照片,图像,照片,图)
为什么像'芝加哥天际线照片'这样的标题会被保存到数据库?
答
排除将赶上“照片”,而不是“天际线照片”,也不是“芝加哥的天际线照片” ......它只检查整个属性。
你会与自定义验证更好。
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(图片打印照片图片照片图片)&“asdf图片和图片”.split'然后'errors.add(:title,“不能包含单词:#{invalid_words.join(',')}“)if invalid_words.any?'。将图像单词列表移动到常量也是理想的。 – pdobb 2015-04-01 02:27:20
伟大的建议@pdobb – SteveTurczyn 2015-04-01 06:10:46
我怎么能修改功能不包括数字或括号? – 2015-04-01 23:24:40