Padrino + FactoryGirl not performing Lazy Loading

131 views Asked by At

I'm developing my thesis on Padrino, using Active Record as ORM and FactoryGirl as Mocking framework.

I'm facing a strange behavior.

I've two models: User and 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').

My association is working well, but only after performing a reload on parent object.

Here are the snippets related to this issue: https://bitbucket.org/snippets/cuscos/MbdAK

If I start a 'Padrino Console' and create a user manually, this is the current behavior:

$ 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

It seems that ActiveRecord isn't performing the Lazy Loading for any reason.

Does anyone know why is this happening?

Thanks for all support so far.

1

There are 1 answers

0
Mauricio Klein On BEST ANSWER

For those who it may interest, here is the solution I'm adopting to solve this problem:

In User factory, instead:

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

Do:

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

It's not a proper solution, but solved my problem for now.

Cheers o/