7

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?

Nitish Parkar
  • 2,838
  • 1
  • 19
  • 22

2 Answers2

13

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
shweta
  • 8,019
  • 1
  • 40
  • 43
2

It's pretty clear that it would try to access a user_id field since you are accessing the relationship from an instance of the User class.

Try setting :association_foreign_key => "follower_id" in your followers relationship and setting :association_foreign_key => "followee_id" in your followees relationship.

Ashitaka
  • 19,028
  • 6
  • 54
  • 69