我有以下型号
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
1 回答
我认为这是问题#1198的结果 . 设置关系后尝试重新加载对象 .
https://github.com/mongoid/mongoid/issues/1198