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
- user = User.find_by_email(‘[email protected]’)
- group = Group.new
- group.title = “First group”
- group.save(false)
- membership = Membership.new
- membership.group = group
- membership.user = user
- membership.credit = 10
- membership.save(false)
- puts “membership 1”
- user.groups.each do |g| puts g.title end
-
No problem here, output is :
-
membership 1
-
First group
- group2 = Group.new
- group2.title = “Second group”
- group2.save(false)
- membership2 = Membership.new
- membership2.group = group2
- membership2.user = user
- membership2.credit = 15
- membership2.save(false)
- puts “membership 2”
- user.lists.each do |g| puts g.title end
-
Output is only :
-
membership 2
-
First group
- user2 = User.find_by_email(‘[email protected]’)
- puts “memberships”
- user2.groups.each do |g| puts g.title end
-
Output is :
-
memberships
-
First group
-
Second group
Why was my first group dynamically added to the user’s groups, and not
the second one ?
Thank you for your attention