本文介绍了查找具有所有关联记录的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,

我们有一个人"和最喜欢"的模型.

we have a "Person" and "Favorite" models.

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

"Favorite" is what this person likes: "music", "video", "sport", "internet", "traveling" etc.

人"HABTM收藏"和收藏"HABTM人"

"Person" HABTM "Favorites", and "Favorite" HABTM "Persons"

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

I need to find a Person, that has ALL listed "Favorites. For example, find a person, that likes "music", "traveling" and "sport".

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

How it can be done, using ActiveRecord.find method ?

推荐答案

@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}")

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

You'll need something like this to find people with all favourites rather than any combination of favourites. This is based on the assumption that you have an array of favourite objects, rather than a collection of strings.

兼容 Rails 4 的解决方案:

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

这篇关于查找具有所有关联记录的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 20:18