7

在我的应用程序中,一个用户可以关注很多用户,并且可以被很多用户关注。我尝试使用 has_and_belongs_to_many 关联对此进行建模

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。我错过了什么吗?

4

2 回答 2

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
于 2013-02-25T06:14:02.507 回答
2

很明显,它会尝试访问一个user_id字段,因为您正在从User类的实例访问关系。

尝试设置:association_foreign_key => "follower_id"你的followers关系和设置:association_foreign_key => "followee_id"你的followees关系。

于 2013-02-25T00:10:31.200 回答