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

Untitled

By: a guest on Jul 29th, 2012  |  syntax: None  |  size: 0.58 KB  |  hits: 15  |  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. Custom validation in Rails
  2. class Comment < ActiveRecord::Base
  3.   validates :post_id, presence: true, if: :post_is_published
  4.  
  5.   ...
  6.   def post_is_publised
  7.     post && post.published
  8.   end
  9. end
  10.        
  11. class Comment < ActiveRecord::Base
  12.   validates :post_id, :presence => true, :if => :post_is_published
  13.  
  14.   def post_is_publised
  15.     post.try(:published)
  16.   end
  17. end
  18.        
  19. class Comment < ActiveRecord::Base
  20.   validate :post_has_to_be_published
  21.  
  22.   def post_has_to_be_published
  23.     unless post.try(:published)
  24.       self.errors.add(:base, "you can add comments only to published posts")
  25.     end
  26.   end
  27. end