2016-02-07 102 views
2

有沒有辦法做這樣的事情:包括只有某些屬性

Book.includes(authors: {only: :first_name}) 

我只想要屬性,而不是整個模型的作者。

+0

您可以使用'select' –

+0

您可以選擇包含的模型?你能告訴我這是如何工作的嗎?我的選擇繼續從書 – Ashbury

+0

'Book.includes(:authors).select('authors.first_name')' –

回答

0

不,你不能。如果你不希望加載的所有數據,你可以加載書籍,然後運行作者一個單獨的查詢獨自把他們的名字:

books = Book.where(something_here) 
author_ids = books.map(&:author_id) 
author_names = Author.where(id: author_ids).pluck(:id, :first_name) 
0

你可以使用select獲得每個作者的:first_name財產。

authors_first_names = Author.select(:first_name) 

請參閱活動記錄查詢接口的Rails指南中的selecting specific fields

0

如何像:

Book.joins(:authors).select("books.*, authors.name as author_name") 

中所產生的相關實例都將repond到author_name而不執行額外的SQL語句。