如何根据多态关联类型(Rails)应用不同的验证规则? [英] How to apply different validation rule according to polymorphic association type (Rails)?
问题描述
我有Rails多态模型,我想根据关联的类应用不同的验证.
I have Rails polymorphic model and I want to apply different validations according to associated class.
推荐答案
在以下设置中,类名称在_type
列中,例如:
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
注释类将具有commentable_id
和commentable_type
字段. commentable_type
是类名,而commentable_id
是外键.如果您想通过评论验证特定于帖子的评论,则可以执行以下操作:
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
或者,我想我更喜欢:
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
这篇关于如何根据多态关联类型(Rails)应用不同的验证规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!