2013-02-24 31 views
7

在我的應用程序中,用戶可以關注很多用戶,並可以跟隨很多用戶。 我試圖用這個協會has_and_belongs_to_manyRails HABTM自我加入錯誤

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 

同樣是模範,我創建了一個遷移連接表如下:

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 

當我試圖訪問用戶的追隨者(User.first.followers )它會拋出一個錯誤:

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 

我不明白爲什麼它訪問followees_followers.user_id。我錯過了什麼嗎?

回答

13

在設置多對多自聯接時,foreign_key和:association_foreign_key選項很有用。

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 
+1

感謝您的鏈接。現在正在工作 – 2013-02-25 18:50:59

2

很明顯,它會嘗試訪問user_id字段,因爲您正在訪問User類的實例中的關係。

嘗試在您的followers關係中設置:association_foreign_key => "follower_id",並將:association_foreign_key => "followee_id"設置爲您的followees關係。

+0

感謝您的回答。有效。 – 2013-02-25 18:49:32