2011-08-09 36 views
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 

回答

1

最有可能的验证器上Vote不会被解雇。您可以通过添加验证功能并输出内容或引发异常来确认。

class Vote 
    validate :dummy_validator_to_confirmation 

    def dummy_validator_to_confirmation 
    raise "What the hell, it is being called, then why my validations are not working?" 
    end 
end 

如果创建上述的验证User#vote_on不会引发异常后,就已经证实回调不通过vote_on方法烧制Vote。您需要更改您的代码以触发Vote上的回调。也许改变它类似于以下,将有助于:

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 
     vote = bill.votes.new(:value => value, :user_id => self.id, :polco_group_id => g.id, :type => g.type) 
     vote.save 
    end 
    else 
    raise "no polco_groups for this user" # #{self.full_name}" 
    end 
end 

上有mongoid GitHub上的问题跟踪,使级联回调到嵌入文档的。现在回调只能在正在发生持久性操作的文档上触发。

+0

我试过你说的,但得到/Users/Tim/.rvm/gems/[email protected]/gems/activemodel-3.1.0.rc5/lib/active_model/validations/validates.rb :87:在'validates'中:您需要提供至少一个验证(ArgumentError) – bonhoffer

+0

在阅读文档时,我无法找到没有monkeypatching的自定义验证器。如果我使用validates_presence_of,那么验证器会触发并正常工作。 – bonhoffer

+0

对不起,有一个错字,'validates'应该是'validate'。在再次查看文档定义时,我注意到'Vote'嵌入在'Bill'中,它可能与此有关。如果存在验证器正确触发,唯一性也会被解雇。您可以在创建新记录时发布在mongodb上触发的查询吗? – rubish