Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 18th, 2012  |  syntax: None  |  size: 0.46 KB  |  hits: 19  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Rails HABTM checkbox validation
  2. model Profile
  3.   has_and_belongs_to_many :browsers
  4. end
  5.  
  6. model Browser
  7.   has_and_belongs_to_many :profiles
  8. end
  9.        
  10. validate :must_have_at_least_one_browser
  11.  
  12. private
  13.  
  14.   def must_have_at_least_one_browser
  15.     if browsers.blank?
  16.       errors.add(:base, 'You must select at least one browser')
  17.     end
  18.   end
  19.        
  20. def must_have_at_least_one_browser
  21.     errors.add(:base, 'You must select at least one browser') unless browser_ids.count > 0
  22.   end