如何根据多态关联类型(Rails)应用不同的验证规则?

2024-01-02

我有 Rails 多态模型,我想根据关联类.


类名位于_type例如以下设置中的列:

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

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

评论类将会有commentable_id and commentable_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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何根据多态关联类型(Rails)应用不同的验证规则? 的相关文章

随机推荐