查找记录,具有所有相关记录 [英] Find record, that has ALL associated records

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

问题描述

说,

我们有一个人和最爱模式。

收藏夹就是这个人喜欢:音乐,视频,运动,互联网,旅游等

人HABTM收藏夹和收藏夹HABTM人

我需要找一个人,已经全部上市的收藏夹。比如,找一个人,是喜欢音乐,旅游和运动。

如何是可以做到的,使用ActiveRecord.find方法?

解决方案

  @people = Person.find的(:所有,
   :加入=> :我的最爱,
   :选择=> 的人。*,COUNT(收藏夹)favourite_count
   :条件=> {:最爱=> @array_of_favourites},
   :组=> persons.id有favourite_count = #{@array_of_favourites.count})
 

您需要这样的事找人,所有的最爱,而不是的的收藏夹中的任意组合。这是基于你有喜欢的对象的数组,而不是字符串集合的假设。

轨道4兼容的解决方案:

  @people = Person.joins(:收藏)
  。凡(收藏夹:{ID:@array_of_favourites})
  。集团(people.id)
  .having(计数(favourites.id)= #{@array_of_favourites.count})
 

Say,

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

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

"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".

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 compatible solution:

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆