neo*_*eon 11 activerecord scope ruby-on-rails associations ruby-on-rails-3
背景:
在我的设置中,用户通过CommunityUser拥有许多社区,而社区通过CommunityPost拥有许多帖子.如果遵循,则用户通过社区拥有许多帖子.
has_many :community_users
has_many :communities, through: :community_users
has_many :posts, through: :communities
Run Code Online (Sandbox Code Playgroud)
鉴于上述User.rb,调用"current_user.posts"会返回与current_user共同拥有一个或多个社区的帖子.
题:
我希望改进该关联,以便调用"current_user.posts"仅返回其社区是current_user社区的完整子集的帖子.
因此,给定一个current_ids为[1,2,3]的current_user,调用"current_user.posts"只会产生那些"community_ids"数组为1,[2],[3],[1,2]的帖子, [1,3],[2,3]或[1,2,3].
我一直在研究范围在这里,但似乎无法查明如何成功地做到这一点?
Ric*_*eck 11
好问题......
我的直接想法:
-
ActiveRecord Association Extension
这些基本上允许您为关联创建一系列方法,允许您确定特定条件,如下所示:
#app/models/user.rb
has_many :communities, through: :community_users
has_many :posts, through: :communities do
def in_community
where("community_ids IN (?)", user.community_ids)
end
end
Run Code Online (Sandbox Code Playgroud)
-
您可以在关联中使用条件,如下所示:
#app/models/user.rb
has_many :posts, -> { where("id IN (?)", user.community_ids) }, through: :communities #-> I believe the model object (I.E user) is available in the association
Run Code Online (Sandbox Code Playgroud)
-
我原本以为这是你最好的选择,但是看得更深,我认为只有当你想使用不同的联想名称时
指定has_many:through查询使用的源关联名称.只有在无法从关联中推断出名称时才使用它.has_many:订阅者,通过::订阅将寻找订阅者或订阅者订阅者,除非给出了:来源.
说实话,这是需要一些思考的问题之一
首先,你如何存储/调用community_ids
数组?它是直接存储在数据库中,还是通过ActiveRecord方法访问Model.association_ids
?
期待着进一步帮助您!