Rails HABTM self join error
Asked Answered
D

2

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?

Decurrent answered 24/2, 2013 at 20:1 Comment(0)
C
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
Cutcherry answered 25/2, 2013 at 6:14 Comment(0)
S
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.

Sitting answered 25/2, 2013 at 0:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.