如何根据多态关联类型(Rails)应用不同的验证规则? [英] How to apply different validation rule according to polymorphic association type (Rails)?

查看:72
本文介绍了如何根据多态关联类型(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_idcommentable_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆