我正在尝试列出用户跟踪用户发布的所有帖子,但不确定如何正确设置关联。这已经以各种形式进行了讨论,但我无法找到适用于这种情况的确定答案。我目前的协会如下:
user.rb:
has_many :followers, :class_name => 'UserFollower', :foreign_key => 'user_id'
has_many :following, :class_name => 'UserFollower', :foreign_key => 'follower_id'
has_many :posts
user_follower.rb:
belongs_to :user
belongs_to :follower, :class_name => 'User'
post.rb
belongs_to :user
我希望能够做类似current_user.following_user_posts的事情。所以我试图在我的user.rb中定义一个关联,如:
has_many :following_user_posts, :through => :following
显然这不太对,但我哪里错了?
答案 0 :(得分:0)
Michael hartle使用他的Micropost.from_users_followed_by方法http://ruby.railstutorial.org/chapters/following-users#sec-a_first_feed_implementation
在他的教程中准确回答了这个问题。答案 1 :(得分:0)
想出这个,似乎是一个简单的问题,但术语使它非常混乱。我在user.rb中有以下内容:
has_many :user_followers
has_many :followers, :through => :user_followers, :source => :follower #the users that are following this user
has_many :user_followings, :class_name => 'UserFollower', :foreign_key => "follower_id"
has_many :following, :through => :user_followings, :source => :user #the users that this user is following
has_many :following_user_posts, :through => :user_followings, :source => :posts
在我的user_follower.rb中:
belongs_to :user
belongs_to :follower, :class_name => 'User'
has_many :posts, :through => :user, :source => :posts
结果查询使用了2个内部联接 - 我不知道它的扩展程度如何,但它在开发时对我来说很好。所以现在,我可以简单地使用current_user.following_user_posts