【问题标题】:Filtering on a field in a has_many through association通过关联过滤 has_many 中的字段
【发布时间】:2014-01-24 00:51:53
【问题描述】:

我无法找到直接与 Active Record 的关系过滤 has_many 的最佳方法。我在这里找到了一堆几乎解决问题的帖子,但没有一个答案对我有用。

组:

     has_many :taggings, as: :taggable
     has_many :tags, :through => :taggings

用户:

     has_many :taggings, as: :taggable
     has_many :tags, :through => :taggings

我想查找所有标签与单个组标签匹配的用户

以下方法有效,但我宁愿用查询组合列表。

    def interest_matches
      matched_users = Array.new
      self.tags.uniq.each do |tag|
        tag.users.map{ |u| matched_users.push(u) unless matched_users.include?(u) }
      end
      matched_users
    end

非常感谢任何建议!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord has-many-through arel


    【解决方案1】:

    我假设您正在对一组标签中的标签调用 interest_matches,

    次要注意:您在函数的第 1 行和第 3 行调用了 self.tags.uniq 两次。还有,

    unless matched_users.include?(u) 
    

    上面将每次遍历数组以检查数组中是否存在用户,这不是最佳选择!下次只需在最后调用 .uniq 方法即可。

    无论如何,要回答您的问题,您可能希望连接表访问用户的标签。

    方法,可能有效,也可能无效(希望有效):

     @matched = []
     group_of_tags = (i'm assuming this is predefined)
     @matched << User.joins(:tags).where(tag_name: group_of_tags.pluck(:name))
     @matched.uniq
    

    这不是 100%,但试一试 :)

    【讨论】:

      猜你喜欢
      • 2015-01-27
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 2012-10-01
      • 2021-12-27
      • 2012-06-20
      • 1970-01-01
      相关资源
      最近更新 更多