Has many through : dynamic join on creation

Hello,

I have a User ActiveRecord model and a Group AR model joined by has_many
:through Membership. It’s not a HBTM because I need an extra attribute
for the memberships.

I tried to fill my dev site with some data added via a migration file. I
want to create two groups, and add a user to them. Below is the code I
use, and a description of the behaviour I don’t understand.

Code : - fold - unfold

  1. user = User.find_by_email(‘[email protected]’)
  2. group = Group.new
  3. group.title = “First group”
  4. group.save(false)
  5. membership = Membership.new
  6. membership.group = group
  7. membership.user = user
  8. membership.credit = 10
  9. membership.save(false)
  10. puts “membership 1”
  11. user.groups.each do |g| puts g.title end
  12. No problem here, output is :

  13. membership 1

  14. First group

  15. group2 = Group.new
  16. group2.title = “Second group”
  17. group2.save(false)
  18. membership2 = Membership.new
  19. membership2.group = group2
  20. membership2.user = user
  21. membership2.credit = 15
  22. membership2.save(false)
  23. puts “membership 2”
  24. user.lists.each do |g| puts g.title end
  25. Output is only :

  26. membership 2

  27. First group

  28. user2 = User.find_by_email(‘[email protected]’)
  29. puts “memberships”
  30. user2.groups.each do |g| puts g.title end
  31. Output is :

  32. memberships

  33. First group

  34. Second group

Why was my first group dynamically added to the user’s groups, and not
the second one ?

Thank you for your attention

Maybe a caching weirdness ?
Is my explanation clear enough ?