【问题标题】:acts-as-taggable-on - How do you get Tags by Parent object充当可标记-您如何通过父对象获取标记
【发布时间】:2011-08-31 21:17:31
【问题描述】:

如果我有两个模型 Buckets 和 Photos。桶有_许多照片和照片属于_一个桶。如果我随后使用acts-as-taggable-on gem 为照片添加标签。按桶获取唯一标签列表的最佳方法(惯用且性能良好)是什么?还是单个桶?

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-plugins


    【解决方案1】:

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

    # 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.includes(:photos).includes(:tags).find(params[:id])
    

    如果基准不好,你应该使用 SQL,但是你会失去注入 & co 的语法糖。

    【讨论】:

    • 好的。想我明白你的方向。 +1 - 让我测试一下,看看我是否可以将你写的内容也适应 buckets#index 方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    相关资源
    最近更新 更多