tesserakt
tesserakt

Reputation: 3331

Polymorphic association validation?

Is there any way to validate that a polymorphic association is only related to one item? for example, if I have a comments that are polymorphic and can be on photos, posts, etc. I want to ensure that if I am adding a comment to a posts' list of comments, that if the comment is already associated with the post, the add will fail. (validation uniqueness error). Any ideas?

Upvotes: 3

Views: 948

Answers (1)

bjg
bjg

Reputation: 7477

So I'm guessing 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

Assuming your Comment model has a couple of attributes like author and body (that you want to be unique) then you could create a custom validation in that model like this:

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

I've also assumed that comments are created something like this:

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

Upvotes: 6

Related Questions