Reputation: 71101
If I have two models Buckets and Photos. Buckets has_many Photos and Photo belongs_to a Bucket. If I then added tagging to photos using the acts-as-taggable-on gem. What is the best way (idiomatic and performs well) to get a unique list of tags by Bucket? or for a single Bucket?
Upvotes: 0
Views: 403
Reputation: 19176
Something like this should meet your request
# in your bucket class
def tag_list
photos.inject([]) do |tags, photo|
# with inject syntax
tags + photo.tags.map(&:name) # remove the maps call if you need tag objects
end.uniq
end
def alternative_tag_list
# this code is even simpler, return unique tags
photos.map { |p| p.tags }.flatten.uniq
end
You should benchmark them. They should perform well with a few data and you can always use memoization or cache for the result. You can reduce the number of queries needed by fetching your bucket object including both photos and tags with includes() as in
@bucket = Bucket.includes(:photos).includes(:tags).find(params[:id])
If the benchmark is not good you should go with SQL, but then you're going to loose syntactic sugar of inject & co.
Upvotes: 1