2015-03-31 216 views
0

排除特定的詞我有我的照片模型title屬性。我不希望用戶添加詞語,如...圖片,打印,照片,圖像,照片,PIC被保存到數據庫

我在這個地方驗證,但它似乎並沒有試圖創建時要撿起來/更新標題

驗證:標題,排除:{內:%重量(圖象,打印,照片,圖像,照片,圖),

我嘗試了:在以及

驗證:標題,排除:{在:%(重量)(圖象,打印,照片,圖像,照片,圖)

爲什麼像'芝加哥天際線照片'這樣的標題會被保存到數據庫?

回答

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 
+0

可能會節省一些蜱使用數組交集。 Plus可以包含錯誤信息中的所有無效字:'invalid_words =%w(圖片打印照片圖片照片圖片)&「asdf圖片和圖片」.split'然後'errors.add(:title,「不能包含單詞:#{invalid_words.join(',')}「)if invalid_words.any?'。將圖像單詞列表移動到常量也是理想的。 – pdobb 2015-04-01 02:27:20

+0

偉大的建議@pdobb – SteveTurczyn 2015-04-01 06:10:46

+0

我怎麼能修改功能不包括數字或括號? – 2015-04-01 23:24:40