简体   繁体   中英

Filter belongs_to items in rails

I have Bookshelf model that has_many :books , and i need to filter books by bookshelf.category_id

books: id, bookshelf_id
 belongs_to: bookshelf

bookshelf: id, category_id
 has_many :books

Example that i have in mind but it does not works:

- @books.where(bookshelf: {category_id: 5 }).each do |book|

由于您具有清晰的层次结构,因此应该首先查找书架,然后获取书集

BookShelf.where(category_id: 5).books

Use joins to filter the record. Try this

@books = Book.joins(:bookshelf).where('bookshelves.category_id =?', 5)

I hope this would be helpful.

@books = Book.joins(:bookshelves).where(bookshelf: { category_id: 5 })

如果您已经有@books对象并想对其进行查询,则可以使用,

@books.where('bookshelf_id in (?)', Bookshelf.where(category_id: 5).pluck(:id))

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