2016-02-07 170 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语句。