【问题标题】:Custom scope on has_many, :through association (Rails 4)has_many 上的自定义范围,:通过关联(Rails 4)
【发布时间】:2014-07-06 04:04:05
【问题描述】:

上下文

在我的设置中,用户通过 CommunityUser 拥有许多社区,而社区通过 CommunityPost 拥有许多帖子。如果遵循然后,该用户通过社区有很多帖子。

用户.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”仅返回其社区是 current_user 社区的完整子集的那些帖子。

因此,给定一个 current_user 的 community_ids 为 [1,2,3],调用“current_user.posts”只会产生那些“community_ids”数组为1、[2]、[3]、[ 1,2]、[1,3]、[2,3] 或 [1,2,3]。

我一直在研究范围 here,但似乎无法确定如何成功完成此任务...

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord scope associations


    【解决方案1】:

    好问题...

    我的直接想法:

    --

    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
    

    --

    Conditional Association

    您可以在关联中使用条件,如下所示:

    #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
    

    --

    Source

    我原本认为这是你最好的选择,但更深入地研究它,我认为只有当你想使用不同的关联名称时

    指定 has_many 使用的源关联名称 :through 查询。仅在无法从 协会。 has_many :subscribers, through: :subscriptions 看起来 对于 :subscribers 或 :subscriber on Subscription,除非 :source 已给出。


    说实话,这是需要思考的问题之一

    首先,您如何存储/调用community_ids 数组?是直接存储在db中,还是通过ActiveRecord方法Model.association_ids访问?

    期待进一步帮助您!

    【讨论】:

    • 您好,抱歉耽搁了!我有点假设这个问题需要一段时间才能得到回答,因为它需要你提到的一些想法。是的,我正在使用 Rails 并为 community_ids 使用 ActiveRecord 方法。
    • 正如你提到的,用户可以使用条件关联:“has_many :posts, ->(user) { where("id IN (?)", user.community_ids) }, through: :communities ",但在这种情况下,我是否还需要以某种方式检查每个帖子的社区?只是大声思考。
    • 旁注:像这样执行 "where("id IN (?)", user.community_ids)" 将返回与“user.community_ids”中的任何一个相关的帖子,而不是返回与社区相关的帖子这是“user.community_ids”的完整子集
    • 你提到的conditional association应该可以工作!
    • @Pavan 你能举个例子吗?
    【解决方案2】:

    您没有显示 CommunityCommunityPost 的模型和关系定义,因此请确保您的 Community 模型上有 has_many :community_postshas_many :posts, through: :community_posts 以及 belongs_to :community 和 @ 987654327@CommunityPost。如果您不需要跟踪 ComunityPost 上的任何内容,您可以在 Community 上使用 has_and_belongs_to_many :posts 和仅包含外键 community_idpost_id 的连接表 communities_posts

    假设您按照我的描述设置了关系,您应该能够只使用current_user.posts 来获得可以进一步链接的关系,并在您调用.all 时返回与用户关联的所有社区的所有帖子在上面。定义您的 Post 模型的任何类方法(例如范围方法)也可以从该关系中调用,因此您应该在其中进行改进,除非这些改进与 CommunityCommunityPost 相关,在这种情况下您可以将它们放在CommunityCommunityPost 型号。实际上很少需要范围的 AR 关系扩展,因为通常您还希望能够独立于您可能使用的任何相关模型来完善模型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-05
      • 1970-01-01
      • 2014-02-25
      • 2015-11-16
      • 2016-08-23
      • 2014-12-16
      • 2013-11-24
      相关资源
      最近更新 更多