开发者

Mongoid reference uniqueness

I'm having this model:

class Vote
  include Mongoid::Document
  include Mongoid::Timestamps

  field 开发者_Go百科: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

The problem is that the validation for user uniqueness per vote is not working, and the same user can create several votes, which is not what I want. Any ideas how to solve that?


Looks like this is a known problem.

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

It is possible to write a custom validation to enforce uniqueness. Here is a quick test:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜