Rails HABTM self join error

has-and-belongs-to-many, ruby-on-rails-3

Solution

The :foreign_key and :association_foreign_key options are useful when setting up a many-to-many self-join.

class User < ActiveRecord::Base
  has_and_belongs_to_many :followers, class_name: "User", foreign_key: "followee_id", join_table: "followees_followers", association_foreign_key: "follower_id"
  has_and_belongs_to_many :followees, class_name: "User", foreign_key: "follower_id", join_table: "followees_followers", association_foreign_key: "followee_id"
end

Problem

In my application a user can follow many users and can be followed by many users. I tried to model this using has_and_belongs_to_many association ``` class User < ActiveRecord::Base has_and_belongs_to_many :followers, class_name: "User", foreign_key: "followee_id", join_table: "followees_followers" has_and_belongs_to_many :followees, class_name: "User", foreign_key: "follower_id", join_table: "followees_followers" end ``` Also, I created a migration for join table as follows: ``` class FolloweesFollowers < ActiveRecord::Migration def up create_table 'followees_followers', :id => false do |t| t.column :followee_id, :integer t.column :follower_id, :integer end end def down drop_table 'followees_followers' end end ``` when I try to access followers of a user (User.first.followers) it throws an error: ``` SQLException: no such column: followees_followers.user_id: SELECT "users".* FROM "users" INNER JOIN "followees_followers" ON "users"."id" = "followees_followers"."user_id" WHERE "followees_followers"."followee_id" = 1 ``` I don't understand why is it accessing followees_followers.user_id. Am I missing something?

Original source