Hi, I'm trying to get to grips with this type of association in Rails
I have the following three models:
User
has_many: 'memberships'
has_many: groups, :through => 'memberships'
Membership
belongs_to: 'user'
belongs_to 'group'
Group
has_many: 'memberships'
has_many: 'users', :through => 'memberships'
I have a before_create method which adds a new user to a default user group.
user.rb
attr_accessor :group_ids
before_create :add_user_to_default_group
after_save :update_groups
def add_user_to_default_group
self.group_ids = [1]
end
#after_save callback to handle group_ids
def update_groups
unless group_ids.nil?
self.memberships.each do |m|
m.destroy unless group_ids.include?(m.group_id.to_s)
group_ids.delete(m.group_id.to_s)
end
group_ids.each do |g|
self.memberships.create(:group_id => g) unless g.blank?
end
reload
self.group_ids = nil
end
end
I'm trying to write a test to ensure this is happening correctly.
user = User.new
user.username = 'testuser'
user.email = '[email protected]'
user.password = 'testpass'
user.password_confirmation = 'testpass'
assert user.save
assert user.errors.empty?
assert !user.memberships.empty?
The test passes if I use user.memberships.empty, but not if I use user.groups.empty?. I was under the impression I should be able to access the groups through .groups?
How would I test that the user belongs to a default group called 'Active Users'?
Any advice would be greatly appreciated.
Thanks