Padrino + FactoryGirl 不执行延迟加载

Padrino + FactoryGirl not performing Lazy Loading

我正在写关于 Padrino 的论文,使用 Active Record 作为 ORM,使用 FactoryGirl 作为 Mocking 框架。

我遇到了一个奇怪的行为。

我有两个模型:User 和 Rate。

- User has a 'has_many :rates' association;
- Rate has a 'belongs_to :user' association;
- 'rates' table has an integer attribute named 'user_id' (not created with 'references' on migration, but directly with 'integer').

我的关联运行良好,但仅在对父对象执行重新加载之后。

以下是与此问题相关的片段: https://bitbucket.org/snippets/cuscos/MbdAK

如果我启动 'Padrino Console' 并手动创建用户,这是当前行为:

$ user = FactoryGirl.create(:user_with_rates)
$ user.rates.length          # Received '0', but expected '1'
$ user.rates.all.length     # Received '1', OK
$ user.reload!
$ user.rates.length          # Now I'm receiving '1' correctly

似乎 ActiveRecord 出于某种原因没有执行延迟加载。

有人知道为什么会这样吗?

感谢大家的支持。

对于那些可能感兴趣的人,这是我用来解决这个问题的解决方案:

在用户工厂中,改为:

after(:create) do |user, evaluator|
  create_list(:rate, evaluator.rates_count, user: user)
end

做:

after(:create) do |user, evaluator|
  user.rates << create_list(:rate, evaluator.rates_count, user: user)
end

这不是一个合适的解决方案,但暂时解决了我的问题。

干杯 o/