[英]Filter belongs_to items in rails
I have Bookshelf
model that has_many :books
, and i need to filter books by bookshelf.category_id 我有
has_many :books
Bookshelf
模型,我需要按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. 使用
joins
过滤记录。 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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.