actions -as- tagable -on -如何通过父对象获得标签



如果我有两个模型bucket和Photos。Bucket has_many Photos和Photo belongs_to a Bucket。然后,我使用acts-as- tagable -on gem为照片添加标签。按Bucket获取唯一标记列表的最佳方式(惯用且性能良好)是什么?还是单桶的?

这样的东西应该满足您的要求

# 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

应该对它们进行基准测试。它们在处理少量数据时应该表现良好,并且您总是可以对结果使用记忆或缓存。您可以通过使用includes()获取bucket对象(包括照片和标签)来减少所需的查询次数,如

所示
@bucket = Bucket.includes(:photos).includes(:tags).find(params[:id])

如果基准测试不是很好,你应该使用SQL,但这样你就会失去语法糖注入&有限公司

最新更新