ruby on rails - Exclude specific words from being saved to database -


i have title attribute photo model. not want users add words such ... picture, print, photo, image, photograph, pic

i have validation in place doesn't seem picking when trying create/update title

validates :title, exclusion: { within: %w(picture, print, photo, image, photograph, pic),

i tried :in well

validates :title, exclusion: { in: %w(picture, print, photo, image, photograph, pic)

any ideas why title 'chicago skyline photo' saved db?

exclusion catch "photo" not "skyline photo" nor "chicago skyline photo"... checks entire attribute only.

you'd better off custom validation.

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

edit

to handle case of punctuation or digits , include @pdobb's excellent suggestion...

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 

Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -