title: Ruby on Rails - Accessing data in :has_many => :through association
body: <p>I'm trying to get to grips with this type of association in Rails</p>
  
  <p>I have the following three models:</p>
  
  <pre><code>User
  
  has_many: 'memberships'
  has_many: groups, :through =&gt; 'memberships'
  
  Membership
  
  belongs_to: 'user'
  belongs_to 'group'
  
  Group
  
  has_many: 'memberships'
  has_many: 'users', :through =&gt; 'memberships'
  </code></pre>
  
  <p>I have a before_create method which adds a new user to a default user group.  </p>
  
  <pre><code>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 =&gt; g) unless g.blank?
        end
        reload
        self.group_ids = nil
      end
    end
  </code></pre>
  
  <p>I'm trying to write a test to ensure this is happening correctly.  </p>
  
  <pre><code>user = User.new
  user.username = 'testuser'
  user.email = 'testuser@testdomain.co.uk'
  user.password = 'testpass'
  user.password_confirmation = 'testpass'
  assert user.save
  assert user.errors.empty?
  assert !user.memberships.empty?
  </code></pre>
  
  <p>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?</p>
  
  <p>How would I test that the user belongs to a default group called 'Active Users'?</p>
  
  <p>Any advice would be greatly appreciated.  </p>
  
  <p>Thanks</p>