how to find entries with no tags using acts-as-taggable-on?

拜拜、爱过 提交于 2019-12-23 02:22:16

问题


What's the Right Way(tm) to find the entries that have no tags?

I tried using Entry.tagged_with(nil) but it just returns an empty hash.

I need it so I can list the entries I still need to tag.

Thanks.


回答1:


Without knowing the internals of acts-as-taggable-on I can't think of a neat way that doesn't involve looping queries or raw SQL. This is readable:

need_to_tag = []

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

need_to_tag then holds any untagged Entries.




回答2:


The following seems to work for me:

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

This should support chaining as well. For example, the following should work:

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



回答3:


Here is my solution to find the tagged and untagged photos.

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‘)')

But it works for the Photo model, but can not be chained with other scopes.




回答4:


I realize this is ancient but I just came on a similar need today. I just did it with a simple multiple-query scope:

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)
}

It may not be efficient for huge datasets but it suits my purposes.



来源:https://stackoverflow.com/questions/4574559/how-to-find-entries-with-no-tags-using-acts-as-taggable-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!