Search code examples
ruby-on-railsmodelpolymorphic-associations

How to apply different validation rule according to polymorphic association type (Rails)?


I have Rails polymorphic model and I want to apply different validations according to associated class.


Solution

  • The class name is in the _type column for instance in the following setup:

    class Comment
       belongs_to :commentable, :polymorphic => true
    end
    
    class Post
      has_many :comments, :as => :commentable
    end
    

    the comment class is going to have the commentable_id and commentable_type fields. commentable_type is the class name and commentable_id is the foreign key. If you wanted to to a validation through comment for post-specific comments, you could do something like this:

    validate :post_comments_are_long_enough
    
    def post_comments_are_long_enough
      if self.commentable_type == "Post"  && self.body.size < 10
        @errors.add_to_base "Comment should be 10 characters"
      end
    end
    

    OR, and I think I like this better:

    validates_length_of :body, :mimimum => 10, :if => :is_post?
    
    def is_post?
      self.commentable_type == "Post"
    end
    

    if you have several validations, I would recommend this syntax instead:

    with_options :if => :is_post? do |o|
      o.validates_length_of :body, :minimum => 10
      o.validates_length_of :body, :maximum => 100
    end