2

所以,我有一个系统,用户可以关注作者(其他用户)。

用户模型:

  class User < ActiveRecord::Base
    has_many :author_following, class_name: 'Following'
    has_many :following, through: :author_following, source: :author
    has_many :followers, foreign_key: 'author_id', through: :author_following, source: :user
  end

以下型号:

  class Following < ActiveRecord::Base
    belongs_to :user
    belongs_to :author, foreign_key: 'author_id', class_name: "User"
  end

问题:我能够获得我正在关注的作者列表,但我能够获得我的关注者列表。


Given:u是一个有效的用户,正在关注其他人并拥有关注者

u.following生成以下 SQL:

    SELECT "users".* FROM "users" INNER JOIN "followings" ON "users"."id" = "followings"."author_id" WHERE "followings"."user_id" = $1  [["user_id", 1]]

哪个是对的..

u.followers生成以下 SQL:

    SELECT "users".* FROM "users" INNER JOIN "followings" ON "users"."id" = "followings"."user_id" WHERE "followings"."user_id" = $1  [["user_id", 1]]

哪个是错的。。

理想情况下,此 SQL 将是WHERE "followings"."author_id" = $1

4

3 回答 3

4

当然,我在发布问题后认为这是您的权利。但是,如果您认为有更优雅的方法可以做到这一点,请发表评论:)

为了解决,我改变了:

用户模型:

  class User < ActiveRecord::Base
    has_many :author_following, class_name: 'Following'
    has_many :following, through: :author_following, source: :author
    has_many :author_followers, foreign_key: 'author_id', class_name: 'Following'
    has_many :followers, through: :author_followers, source: :user
  end

以下型号:

  class Following < ActiveRecord::Base
    belongs_to :user
    belongs_to :author, class_name: "User"
  end
于 2013-08-27T19:39:24.603 回答
1

另一种方法是使用has_and_belongs_to_many. 不需要第二个模型。

class User < ActiveRecord::Base
  has_and_belongs_to_many :followers, class_name: 'User', foreign_key: 'follower_id'
  has_and_belongs_to_many :followees, class_name: 'User', foreign_key: 'followee_id'
end

# Migration
create_table :followees_followers do |t|
  t.belongs_to :followee
  t.belongs_to :follower
end

这更简单,但验证部分(比如验证某人是作者)需要在用户模型中完成

于 2013-08-27T19:57:45.343 回答
0

@Billy Chan 上面的答案很接近,但您还需要使用“association_foreign_key”指定关系的另一方,并在我们这边用 followee_id 切换 follower_id。此外,连接表实际上是 users_users。

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

  # Migration
    create_table :users_users do |t|
       t.belongs_to :followee
       t.belongs_to :follower
    end

现在 User.followers 和 User.followees 按预期工作

于 2016-11-11T00:49:25.147 回答