I can't seem to get bidirectionality working on my Rails models. For example, in the rails console, when I execute the following:
r = Role.new
u = User.new
r.users << u
r.users
u.roles
The rails console states that role has users, but the user has no roles. If I save the role, then pull the user from the db, it has a role like it should, but the role's state doesn't stay consistent between the two objects.
I only have one db migration. Here is the code related to the two models (excluding simple data fields)
create_table :users do |t|
end
create_table :roles do |t|
end
create_join_table :users, :roles
Database itself also looks normal. Here are the two models
class User < ApplicationRecord
has_and_belongs_to_many :roles
# unrelated
has_many :committee_enrollments
has_many :committees, through: :committee_enrollments
end
class Role < ApplicationRecord
has_and_belongs_to_many :users
# unrelated
has_and_belongs_to_many :committees
end
All my associations are doing this. I can only get relations being set automatically when I specify inverse_of:. However, specifying source: doesn't work for through: relations.
ruby 2.7.1p83, Rails 6.1.3, postgresql 12.5, Ubuntu WSL
Edit: ok so I understand the relationship won't exist until I save. However, I am still having an issue with data inconsistency. For example:
r = Role.first
r2 = r.users.first.roles.first
r.role_name == r2.role_name
=> true
r.role_name = "changed"
r.role_name == r2.role_name
=> false
according to the documentation, this second one should be true.