开发者

How to apply different validation rule according to polymorphic association type (Rails)?

I have Rails polymorph开发者_开发百科ic model and I want to apply different validations according to associated class.


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


The validates_associated method is what you need. You just have to link this method to the polymorphic model and it will check if the associated models are valid.

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜