开发者

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

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

I tried using Entry.tagged开发者_如何学C_with(nil) but it just returns an empty hash.

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

Thanks.


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


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜