Mongoid关联,延迟加载等等

时间:2011-08-31 03:43:48

标签: ruby-on-rails mongodb associations mongoid

我有以下型号

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 个答案:

答案 0 :(得分:1)

我认为这是问题#1198的结果。设置关系后尝试重新加载对象。

https://github.com/mongoid/mongoid/issues/1198