通过某种东西来实现自己

时间:2013-08-27 19:26:05

标签: ruby-on-rails ruby-on-rails-3 activerecord

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

用户模型:

  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

3 个答案:

答案 0 :(得分:2)

当然,我在发布问题后认为你是对的。但是,如果您认为有更优雅的方式,请评论:)

要解决,我改变了:

用户模型:

  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

答案 1 :(得分: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

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

答案 2 :(得分:0)

@Billy Chan的上述回答很接近,但您还需要指定关系的另一面以及&#34; association_foreign_key&#34;,并在我们这边使用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按预期工作