我有以下型号
class Vote include Mongoid::Document include Mongoid::Timestamps field :value, :type => Symbol # can be :aye, :nay, :abstain, :present belongs_to :user belongs_to :polco_group belongs_to :bill
和比尔
class Bill has_many :votes
和用户
class User has_many :votes
我正在尝试实施以下测试
b = Bill.new @user1.vote_on(b, :aye) assert_equal :aye, b.voted_on?(@user1)
此测试失败,因为如果我按照这些步骤操作,则b.votes.all
为空,但b.votes
包含我们需要的数据。但是,如果我打开rails控制台,我会认为b.votes
是[],但是如果我按照这些步骤填充b.votes.all
。我确信这里有一些简单的东西。何时b.votes []和.all需要?
我的方法:
# in User.rb def vote_on(bill, value) # test to make sure the user is a member of a group my_groups = self.joined_groups unless my_groups.empty? unless bill.voted_on?(self) my_groups.each do |g| unless Vote.create(:value => value, :user => self, :polco_group => g, :bill => bill) raise "vote not valid" end end end #bill.save! else raise "no joined_groups for this user" end end
和
# in Bill.rb def voted_on?(user) if votes = self.votes.all.select{|v| v.user == user} votes.map{|v| v.value}.first else nil end end