Skip to content

Instantly share code, notes, and snippets.

@DavidVII
Last active November 19, 2015 19:51
Show Gist options
  • Save DavidVII/c17fcf3c536365ccbb27 to your computer and use it in GitHub Desktop.
Save DavidVII/c17fcf3c536365ccbb27 to your computer and use it in GitHub Desktop.
Return a list of tagged (polymorphic) records.

Models

  • Tag
  • Tagging (join table)
  • Taggable (Polymorphic: Video, Article, Recipe)
class TaggedResource < JSONAPI::Resource
immutable
filter :tag
def self.apply_filter(records, filter, value, options)
case filter
when :tag
value.map!(&:capitalize)
tags = Tag.where(name: value)
records.select { |r| (r.tags & tags).any? }
else
records
end
end
def self.records(options = {})
Tagging.includes(:taggable).collect(&:taggable).uniq
end
def self.find(filters, options = {})
context = options[:context]
records = filter_records(filters, options)
sort_criteria = options.fetch(:sort_criteria) { [] }
order_options = construct_order_options(sort_criteria)
records = apply_pagination(records, options[:paginator], order_options)
resources = []
records.each do |model|
resources.push resource_for(resource_type_for(model)).new(model, context)
end
resources
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment