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?
+1
A:
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)
bjg
2010-07-06 21:36:42
actually, it is a polymorphic with a has_many through a join table, so the polymorphic association is in the join table. I just put a validation on the _id and _type scoped with the id of the item and it worked just fine.
tesmar
2010-07-08 02:32:36