2011-01-01 6 views
1

나는이 모델을 보내고 있습니다 :Mongoid 참조 고유성

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 

문제는 투표 당 사용자 고유성에 대한 유효성 검사가 작동하지 않는 경우, 동일한 사용자가 내가 원하는하지 않은, 몇 표를 만들 수 있다는 것입니다 . 어떤 아이디어를 해결하는 방법?

답변

2

이렇게 보이는 것이 알려진 문제입니다.

http://groups.google.com/group/mongoid/browse_thread/thread/e319b50d87327292/14ab7fe39337418a?lnk=gst&q=validates#14ab7fe39337418a

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 
+0

실제로 다른 모든 유효성 검사가 나와 있습니다. 이것은 참조와 관련되어 있기 때문에 작동하지 않습니다. 유일한 왼쪽 솔루션은 위에 제안한 사용자 정의 유효성 검사기입니다. – khelll