【问题标题】:Find record, that has ALL associated records查找具有所有关联记录的记录
【发布时间】:2010-08-05 15:41:06
【问题描述】:

说,

我们有一个“人”和“最喜欢”的模型。

“最喜欢的”是这个人喜欢的东西:“音乐”、“视频”、“运动”、“互联网”、“旅行”等。

“人”HABTM“收藏”和“收藏”HABTM“人”

我需要找到一个人,其中列出了所有“收藏夹”。例如,找到一个喜欢“音乐”、“旅行”和“运动”的人。

如何做到这一点,使用 ActiveRecord.find 方法?

【问题讨论】:

    标签: ruby-on-rails activerecord find has-and-belongs-to-many


    【解决方案1】:
    @people = Person.find(:all, 
       :joins => :favourites,
       :select => "person.*, count(favourites) favourite_count", 
       :conditions => {:favourites => @array_of_favourites}, 
       :group => "persons.id having favourite_count = #{@array_of_favourites.count}")
    

    你需要这样的东西来找到拥有所有收藏而不是任何组合收藏的人。这是基于您有一个最喜欢的对象数组而不是字符串集合的假设。

    兼容 Rails 4 的解决方案:

    @people = Person.joins(:favourites)
      .where(favourites: { id: @array_of_favourites })
      .group("people.id")
      .having("count(favourites.id) = #{@array_of_favourites.count}")
    

    【讨论】:

      猜你喜欢
      • 2011-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多