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

I have a polymorphic Rails model, and I want to apply various checks according to the corresponding class.

+3
source share
2 answers

The class name is in the column _type, for example, in the following setting:

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

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

the comment class will have commentable_idand fields commentable_type. commentable_typeis the name of the class, and commentable_idis the foreign key. If you want to perform validation through a comment for post-specific comments, you can 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 it’s better for me:

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
+3

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
+1

Source: https://habr.com/ru/post/1754004/


All Articles