vendredi 10 juin 2016

ActiveRecord Caching in tests. Usage of reload

This happens right now in terminal and rails console:

[1] pry(main)> user = FactoryGirl.create(:user)
[2] pry(main)> FactoryGirl.create(:subscription, user:user)
[3] pry(main)> user.subscriptions
[]
[4] pry(main)> user.reload.subscriptions
  User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 5664005]]
  Subscription Load (0.3ms)  SELECT "subscriptions".* FROM "subscriptions" WHERE "subscriptions"."user_id" = $1  [["user_id", 5664005]]
[
    [0] #<Subscription:0x007fec75081470> {
                           :id => 5603375,
                      :user_id => 5664005,
    }
]

I think I know why. In an after_save hook for the user model, there's a method that calls self.subscriptions. I assume that causes ActiveRecord to cache the association for user.subscription until I reload the user right? Is there AR caching that goes on? Is that a feature of AR or Rails? When I create the subscription with an associated user, that does not reload user.subscriptions to point to the newly created subscription even though subscription.user points to said user. Is that right? What is going on behind the scenes here?

Aucun commentaire:

Enregistrer un commentaire