Module: Sequel::Plugins::Tags::ClassMethods

Defined in:
lib/cortex_reaver/support/tags.rb

Overview

Support for taggable models

Instance Method Summary collapse

Instance Method Details

#tagged_with(tags, all = true) ⇒ Object

Returns all models with ALL the following tags:



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/cortex_reaver/support/tags.rb', line 12

def tagged_with(tags, all=true)
  # Find map between this model and tags, e.g. pages_tags
  reflection = self.association_reflection(:tags)
  map = reflection[:join_table]
  own_id = reflection[:left_key]
  
  # The tag IDs to search for
  ids = tags.map { |t| t.id }
  
  # Now filter this model, finding all ids which appear n times with
  # the same model_id in the mapping table, which has been filtered
  # to contain only rows with one of our interesting tags.
  #
  # Man, don't you wish MySQL had intersect?
  if all
    filter(:id =>
      CortexReaver.db[map].filter(:tag_id => ids).group(own_id).having(
        "count(*) = #{ids.size}"
      ).select(own_id)
    )
  else
    filter(:id => 
      CortexReaver.db[map].filter(:tag_id => ids).select(own_id)
    )
  end
end

#tagged_with_any_of(tags) ⇒ Object

Returns all models with ANY of the following tags



7
8
9
# File 'lib/cortex_reaver/support/tags.rb', line 7

def tagged_with_any_of(tags)
  tagged_with(tags, false)
end