简体   繁体   中英

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.

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])

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.

Any help would be appreciated.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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