【问题标题】:how to find entries with no tags using acts-as-taggable-on?如何使用acts-as-taggable-on查找没有标签的条目?
【发布时间】:2011-01-01 15:45:04
【问题描述】:

找到没有标签的条目的正确方法是什么?

我尝试使用Entry.tagged_with(nil),但它只返回一个空哈希。

我需要它,所以我可以列出我仍然需要标记的条目。

谢谢。

【问题讨论】:

    标签: ruby-on-rails acts-as-taggable-on


    【解决方案1】:

    以下似乎对我有用:

    Entry.includes("taggings").where("taggings.id is null")
    

    这也应该支持链接。例如,以下应该可以工作:

    Entry.includes("taggings").where("taggings.id is null").where(foo: "bar")
    

    【讨论】:

      【解决方案2】:

      这是我找到标记和未标记照片的解决方案。

      scope :with_taggings, where('id in (select taggable_id from taggings where taggable_type = ’Photo‘ and context = ’bibs‘)')
      scope :without_taggings, where('id not in (select taggable_id from taggings where taggable_type = ’Photo‘ and context = ’bibs‘)')
      

      但它适用于 Photo 模型,但不能与其他范围链接。

      【讨论】:

      • 两个注意事项: a) 您应该在 SQL 代码中使用单个 '。 MySQL 对 "'" 和 '"' 的处理方式相同,但其他数据库(例如 Postgresql)不这样做。b) 如果不使用它 - 为什么不能将这段代码链接起来?
      【解决方案3】:

      我意识到这很古老,但我今天也遇到了类似的需求。我只是用一个简单的多查询范围做到了:

      scope :untagged, lambda {
        # first build a scope for the records of this type that *are* tagged
        tagged_scope = Tagging.where(:taggable_type => base_class.to_s)
      
        # only fetching the taggable ids
        tagged_scope = tagged_scope.select('DISTINCT taggable_id')
      
        # and use it to retrieve the set of ids you *don't* want
        tagged_ids = connection.select_values(tagged_scope.to_sql)
      
        # then query for the rest of the records, excluding what you've found
        where arel_table[:id].not_in(tagged_ids)
      }
      

      对于大型数据集可能效率不高,但它适合我的目的。

      【讨论】:

        【解决方案4】:

        在不了解acts-as-taggable-on 的内部情况的情况下,我想不出一种不涉及循环查询或原始 SQL 的简洁方法。这是可读的:

        need_to_tag = []
        
        Entry.all.each do |e|
          need_to_tag << e if e.tag_list.blank?
        end
        

        need_to_tag 然后保存所有未标记的条目。

        【讨论】:

        • 谢谢。我希望有更好的方法,但这当然也有效。
        • 有更好的方法吗?这使得一个查询命中数据库。我标记了 5000 条记录,这是不可接受的。
        • 我认为最适合您的方法是在这种情况下使用原始 SQL 查询。
        • ...服务器因内存不足而崩溃。第一次获得 100000 个条目,第二次需要 50000 个条目。
        猜你喜欢
        • 1970-01-01
        • 2011-04-08
        • 2011-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-19
        相关资源
        最近更新 更多