Verification of polymorphic association?

Is there a way to verify that polymorphic association is associated with only one element? for example, if I have comments that are polymorphic and may be in photos, posts, etc. I want to make sure that if I add a comment to the list of comments in posts, that if the comment is already associated with the post, the posting will fail. (check uniqueness error). Any ideas?

+3
source share
1 answer

So, I assume that you have something like this:

class Comment < ActiveRecord::Base
  belongs to commentable, :polymorphic => true
end

class Post < ActiveRecord::Base
  has_many :comments, :as => commentable, :dependent => :destroy
end

class Photo < ActiveRecord::Base
  has_many :comments, :as => commentable, :dependent => :destroy
end

, Comment , author body ( ), :

validate do |comment|
  if comment.commentable_type.constantize.comments.find_by_author_and_body(comment.author, comment.body)
    comment.errors.add_to_base "Duplicate comment added for ..."
  end
end

, :

@post.comments.create(:author => name, :body => comment_text)
+6

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


All Articles