我有这个模特:
class Vote
include Mongoid::Document
include Mongoid::Timestamps
field :vote, :type=>Integer
embedded_in :voteable, :inverse_of => :votes
referenced_in :user
attr_accessible :vote, :user, :voteable
validates :vote,:inclusion => [-1, 1]
validates :user ,:presence=> true,:uniqueness=>true
end
问题是每次投票的用户唯一性验证不起作用,同一个用户可以创建多个投票,这不是我想要的。任何想法如何解决?
答案 0 :(得分:2)
看起来这是一个已知问题。
https://github.com/mongoid/mongoid/issuesearch?state=open&q=validates#issue/373
可以编写自定义验证来强制执行唯一性。这是一个快速测试:
class UserUniquenessValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors[attribute] << "value #{value} is not unique" unless is_unique_within_votes(record, attribute, value)
end
def is_unique_within_votes(vote, attribute, value)
vote.voteable.votes.each do |sibling|
return false if sibling != vote && vote.user == sibling.user
end
true
end
end
class Vote
...
validates :user ,:presence => true, :user_uniqueness => true
end