views:

37

answers:

1

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

+1  A: 

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
Geoff Lanotte
That's the shitty part. Can't access attributes from inside polymorphic model."undefined method `itemable_type' for #<Class:0xb5fd87b0>"
sharas
Life would be perfect otherwise... :(
sharas
if you are writing the above code directly into your class that would fail, it would only be available for an instance, not the class. Add the `define_method` code into a instance method and it should pass.
Geoff Lanotte
Thank you, my mind was screwed up, I slept for a hour and solved everything out.
sharas