[英]Has_many through a has_many in Rails 3.1
我有一个用户模型,该模型允许用户关注其他用户。 每个用户也有很多东西:
class User
has_many :following, :class_name => 'Followings', :foreign_key => 'follower_id'
has_many :things
end
我最终要做的是从用户关注的所有用户那里得到所有东西,并能够对这个查询进行分页。 有什么建议么?
取决于您要如何分离出数据。 这将为您提供所有事物的唯一数组,而无需保留它们属于哪个跟随用户:
@user = User.first
@things = @user.followings.map(&:things).flatten.uniq
这正是has_many:through的作用:
class User
# ...
has_many :followed_users, :through => :followings, :source => :followed
has_many :followed_things, :through => :followed_users, :source => :things
end
:source
选项在Rails API文档中进行了描述。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.