title: ActiveRecord::HasManyThroughOrderError: Cannot have a has_many :through association
body: <p>In my rails app I'm trying to create a system that will reward users with badges for various achievements</p>
  
  <p>created a table 'user_badges'</p>
  
  <p>migration:</p>
  
  <pre><code>class CreateUserBadges &lt; ActiveRecord::Migration[5.1]
    def change
      create_table :user_badges do |t|
  
      t.references :user, foreign_key: true
      t.references :badge, foreign_key: true
  
      t.timestamps
      end
    end
  end
  </code></pre>
  
  <p>model UserBadge:</p>
  
  <pre><code>class UserBadge &lt; ApplicationRecord
  
    belongs_to :user
    belongs_to :badge
  
  end
  </code></pre>
  
  <p>модель Badge:</p>
  
  <pre><code>class Badge &lt; ApplicationRecord
    has_many :users, through: :user_badges
    has_many :user_badges
  end
  </code></pre>
  
  <p>model User:</p>
  
  <pre><code>class User &lt; ApplicationRecord
    ...
  
    has_many :badges, through: :user_badges
    has_many :user_badges
  
    ...
  end
  </code></pre>
  
  <p>when I try to add a badge to the user:</p>
  
  <pre><code>b = Badge.create(title: 'first')
  
  User.last.badges &lt;&lt; b
  </code></pre>
  
  <p>I get this error:</p>
  
  <pre><code>ActiveRecord::HasManyThroughOrderError: Cannot have a has_many 
  :through association 'User#badges' which goes through 
  'User#user_badges' before the through association is defined.
  </code></pre>
  
  <p>also when I simply call:</p>
  
  <pre><code>User.last.badges
  </code></pre>
  
  <p>same error:</p>
  
  <pre><code>ActiveRecord::HasManyThroughOrderError: Cannot have a has_many 
  :through association 'User#badges' which goes through 
  'User#user_badges' before the through association is defined.
  </code></pre>