【问题标题】:Rails ActiveRecord includes all associations after matching queryRails ActiveRecord 包括匹配查询后的所有关联
【发布时间】:2016-06-07 02:45:44
【问题描述】:

像这样在 Rails 中进行查询以通过 tag_id 查找带有标签的照片会在照片上预加载标签,但只有那些与查询中的 tag_ids 匹配的标签...这会在稍后对照片进行序列化时暴露出来..

如何保留所有关联的标签,并返回具有这些特定标签的照片?

使用此查询:Photo.includes(:tags).where("tags.id IN (?)", [2, 5, 10).references(:tags)

我希望所有照片都有标签 2、5 和 10,但如果照片有标签 2 和 3,我希望它在响应中包含标签 3。

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    可能有更好的方法,但我认为这是可行的。

    # Build a query for all photo IDs that have the specified tags.
    photo_ids_query = Photo.joins(:tags)
                           .where(:tags => { :id => [2, 5, 10] })
                           .select("photos.id")
    
    # Load that list of photo IDs using a subquery.
    Photo.includes(:tags)
         .where("photos.id IN (#{photo_ids_query.to_sql})")
    

    【讨论】:

      【解决方案2】:

      我不认为这可以通过单个连接来完成,因为您不能同时将连接表限制为仅具有特定 ID 的那些记录并且限制它。

      我认为您可以使用 Arel 执行此操作,但您需要 2 个连接:一个用于限制 where tags.id in (...)(您可以为其指定一个表别名),另一个用于获取 all em> Tags 连接到每个返回的 Photos(默认一个,以便它成为关联方法使用的一个,例如 photo.tags)。

      也许是这样的......

      photos = Photo.arel_table
      restricted_tags = Tag.arel_table.alias(:restricted_tags)
      Photo.
        includes(:tags).
        joins(
          photos.join(restricted_tags).on(
            tags[:photo_id].eq(photos[:id])  # or whatever your join conditions are in your particular case
          ).join_sources
        ).where(
          restricted_tags.in([2, 5, 10])
        )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-19
        • 2013-09-24
        相关资源
        最近更新 更多