简体   繁体   English

如何查找属于多个模型对象的模型对象

[英]how to find model objects that belong to more than one model object

Suppose I have the models Book and Reading, which has the relationship Book has_many :readings. 假设我有Book and Reading模型,它与Book has_many:readings关系。

Now suppose I want to find all books that have been read in the past week. 现在,假设我想查找过去一周中已阅读的所有书籍。 I know I can find readings created in the past week with something like: readings = Reading.find(:all, :conditions => ["created_at > ?", Date.today - 7]) 我知道我可以找到上周创建的读数,例如:读数= Reading.find(:all,:conditions => [“ created_at>?”,Date.today-7])

However, I'm not sure how to get from that list of readings to a de-duplicated list of books. 但是,我不确定如何从阅读清单到重复数据删除的书籍清单。 I know I can't simply do readings.books because readings is an array and Array#books is not defined. 我知道我不能简单地做readings.books,因为读数是一个数组,而Array#books没有定义。

Any help would be appreciated. 任何帮助,将不胜感激。

Book.joins(:readings).group(:book_id).having("COUNT(*) > 1")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM