我有以下关联:
class User < ActiveRecord::Base
has_many :followers, class_name: "Follow"
has_many :following, class_name: "Follow", foreign_key: "follower_id"
has_many :posts
end
class Follow < ActiveRecord::Base
belongs_to :user
belongs_to :follower, class_name: "User", foreign_key: "follower_id"
end
我希望能够做到这样的事情:
current_user.followers
获取User对象,而不是Follow对象。我为这样的用户做过类似的事情:
class User < ActiveRecord::Base
has_many :post_favorites, class_name: "Favorite"
has_many :favorites, class_name: "Post", through: :post_favorites, source: :post
end
然后我为收件人添加了belongs_to关系:user和:post。这很好。然而,在我试图用追随者完成的事情中,它没有双向关系(这是我能描述它的最佳方式,我猜)因此我无法使用相同的方法使其工作。
有没有一种更智能的方法来解决这个问题?我说的是类似Twitter的“关注/关注者”计划,用户可以关注他人并让其他人关注他们。
我的关注模型只有一个user_id和一个follower_id字段。我想如果我这样做的话会有效:
current_user.followers.each {|follower| follower.user}
但我希望最终能够做到这样的事情:
current_user.followers.posts
答案 0 :(得分:0)
在中间创建一个连接表,并通过它连接到您自己的用户表。
class User
has_many :follows
has_many :followers, :through => :follows, :class_name => "User"
end
class Follow
belongs_to :user
end
create_table :follows do |f|
f.references :user
f.integer :follower_id
end
那样的东西?