I have Rails polymorphic model and I want to apply different validations according to associated class.
views:
37answers:
1
+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
2010-07-10 13:36:35
That's the shitty part. Can't access attributes from inside polymorphic model."undefined method `itemable_type' for #<Class:0xb5fd87b0>"
sharas
2010-07-10 13:44:16
Life would be perfect otherwise... :(
sharas
2010-07-10 13:50:13
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
2010-07-10 14:53:50
Thank you, my mind was screwed up, I slept for a hour and solved everything out.
sharas
2010-07-10 16:28:32