多态关联验证?

tes*_*akt 3 ruby-on-rails

有没有办法验证多态关联只与一个项目相关?例如,如果我有一个多态的评论,可以在照片,帖子等.我想确保如果我在帖子的评论列表中添加评论,如果评论已经与帖子相关联,添加将失败.(验证唯一性错误).有任何想法吗?

bjg*_*bjg 6

所以我猜你有这样的事情:

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
Run Code Online (Sandbox Code Playgroud)

假设你的Comment模型有几个属性authorbody(你想要是唯一的)那么你可以在这个模型中创建一个自定义验证,如下所示:

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
Run Code Online (Sandbox Code Playgroud)

我还假设评论是这样创建的:

@post.comments.create(:author => name, :body => comment_text)
Run Code Online (Sandbox Code Playgroud)