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

問題:フォローしている著者のリストを取得できますが、フォロワーのリストを取得できます。


与えられた: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です。2 番目のモデルは必要ありません。

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

これはより単純ですが、検証部分 (誰かが作成者であることを確認するなど) は User モデルで行う必要があります

于 2013-08-27T19:57:45.343 に答える
0

上記の@Billy Chanの答えは近いですが、関係の反対側も「association_foreign_key」で指定し、follower_idをfollowee_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 に答える