3

我有 Rails 多态模型,我想根据关联的类应用不同的验证。

4

2 回答 2

3

类名在_type列中,例如在以下设置中:

class Comment
   belongs_to :commentable, :polymorphic => true
end

class Post
  has_many :comments, :as => :commentable
end

评论类将有commentable_idandcommentable_type字段。 commentable_type是类名,commentable_id是外键。如果您想通过评论对特定于帖子的评论进行验证,您可以执行以下操作:

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

如果您有多个验证,我会推荐这种语法:

with_options :if => :is_post? do |o|
  o.validates_length_of :body, :minimum => 10
  o.validates_length_of :body, :maximum => 100
end
于 2010-07-10T13:36:35.863 回答
1

validates_associated方法是您所需要的。您只需将此方法链接到多态模型,它将检查关联的模型是否有效。

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
  validates_associated :commentable
end

class Post < ActiveRecord::Base
  has_many :comments, as: commentable

  validates_length_of :body, :minimum => 10
  validates_length_of :body, :maximum => 100
end
于 2017-01-26T14:51:32.193 回答