3
我有以下mongoid模型,范围验证,以防止在一个账单上的多个选票。每票属于用户和组:Mongoid验证唯一性与范围和belongs_to
class Vote include Mongoid::Document field :value, :type => Symbol # can be :aye, :nay, :abstain field :type, :type => Symbol # TODO can delete? belongs_to :user belongs_to :polco_group embedded_in :bill validates_uniqueness_of :value, :scope => [:polco_group_id, :user_id, :type] end
用户有以下方法进行了表决添加到账单:
def vote_on(bill, value) if my_groups = self.polco_groups # test to make sure the user is a member of a group my_groups.each do |g| # TODO see if already voted bill.votes.create(:value => value, :user_id => self.id, :polco_group_id => g.id, :type => g.type) end else raise "no polco_groups for this user" # #{self.full_name}" end end
和嵌入许多法案类:票。这样做的目的是允许用户将他们的投票与不同的团体(“Ruby编码”,“女性”等)相关联,并且运行良好,除了数据库目前允许用户在一张账单上多次投票。我如何获得以下功能?
u = User.last b = Bill.last u.vote_on(b,:nay) u.vote_on(b,:nay) -> should return a validation error
我试过你说的,但得到/Users/Tim/.rvm/gems/[email protected]/gems/activemodel-3.1.0.rc5/lib/active_model/validations/validates.rb :87:在'validates'中:您需要提供至少一个验证(ArgumentError) – bonhoffer
在阅读文档时,我无法找到没有monkeypatching的自定义验证器。如果我使用validates_presence_of,那么验证器会触发并正常工作。 – bonhoffer
对不起,有一个错字,'validates'应该是'validate'。在再次查看文档定义时,我注意到'Vote'嵌入在'Bill'中,它可能与此有关。如果存在验证器正确触发,唯一性也会被解雇。您可以在创建新记录时发布在mongodb上触发的查询吗? – rubish