The class name is in the column _type, for example, in the following setting:
class Comment
belongs_to :commentable, :polymorphic => true
end
class Post
has_many :comments, :as => :commentable
end
the comment class will have commentable_idand fields commentable_type. commentable_typeis the name of the class, and commentable_idis the foreign key. If you want to perform validation through a comment for post-specific comments, you can 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 it’s better for me:
validates_length_of :body, :mimimum => 10, :if => :is_post?
def is_post?
self.commentable_type == "Post"
end
, :
with_options :if => :is_post? do |o|
o.validates_length_of :body, :minimum => 10
o.validates_length_of :body, :maximum => 100
end