Монгоидные ассоциации, ленивая загрузка и все - PullRequest
0 голосов
/ 31 августа 2011

У меня есть следующая модель

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 Ответ

1 голос
/ 05 сентября 2011

Я думаю, что это результат проблемы # 1198.Попробуйте перезагрузить ваш объект после установки отношения.

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

...