上下文
在我的设置中,用户通过CommunityUser拥有许多社区,社区通过CommunityPost拥有许多帖子。如果是这样的话,那么用户就会通过Communities拥有许多帖子。
User.rb
has_many :community_users
has_many :communities, through: :community_users
has_many :posts, through: :communities考虑到上面的User.rb,调用"current_user.posts“会返回与current_user相同的一个或多个社区的帖子。
问题:
我希望改进这个关联,以便调用"current_user.posts“只返回那些社区是当前_user社区的完整子集的帖子。
因此,给定current_user的community_ids为1, 2,3,调用"current_user.posts“只会产生"community_ids”数组为1、2、3、1、2、2、3或1,2,3的帖子。
我一直在研究范围这里,但似乎无法确定如何成功地完成这一任务.
发布于 2014-05-18 08:19:52
问得好..。
我的切身想法:
--
ActiveRecord关联扩展
这些基本允许您为关联创建一系列方法,允许您确定特定的标准,如下所示:
#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--
您可以在关联中使用条件,如下所示:
#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--
来源
我原本以为这是你最好的选择,但更深入地看,我认为只有当你想使用不同的关联名称时,才会这样做。
指定has_many : the查询使用的源关联名称。只有在不能从关联推断名称时才使用它。has_many :订阅者,通过::订阅将查找:订户或订阅的订阅者,除非给出了:source。
老实说,这是一个需要思考的问题。
首先,如何存储/调用community_ids数组?它是直接存储在db中,还是通过ActiveRecord方法Model.association_ids访问?
期待着进一步帮助您!
发布于 2014-05-24 04:29:19
您没有显示用于Community或CommunityPost的模型和关系定义,因此确保在Community模型上有has_many :community_posts和has_many :posts, through: :community_posts,在CommunityPost上有belongs_to :community和belongs_to :post。如果您不需要跟踪ComunityPost上的任何内容,您只需使用Community上的has_and_belongs_to_many :posts和仅包含community_id和post_id外键的联接表communities_posts。
假设您已经设置了我所描述的关系,那么您应该能够使用current_user.posts来获取一个可以进一步链接的关系,当您在它上调用.all时,它会返回与用户关联的所有社区的所有帖子。定义您的Post模型的任何类方法(例如范围方法)也可以从该关系中调用,因此,除非这些精化涉及到Community或CommunityPost,否则您应该将它们放在Community或CommunityPost模型上。实际上,很少需要对作用域进行AR关系扩展,因为通常您也希望能够独立于您可能使用的任何相关模型来改进模型。
https://stackoverflow.com/questions/23716674
复制相似问题