我有post
和author
型号。
author has_many :posts
现在我有author
个posts
是否有一种优雅的方式只将posts'
titles
作为数组,而不是整个post
对象?
所以,不只是author.posts
而是author.posts.only(:title)
之类的东西来获得一系列标题。例如。 ['post1','post2','post3']
。
.only(:title)
语法来自JSON模块并且在这种情况下不起作用但是可能有一些更优雅而不是迭代posts
并将titles
推送到新的select titles from posts where author_id = 23
阵列。查询数据库的内容,如{{1}}。
答案 0 :(得分:5)
使用pluck
author.posts.pluck(:title)
http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck
pluck(column_name)
此方法旨在通过a执行选择 单列作为直接SQL查询返回值为的数组 指定的列名称值与列具有相同的数据类型。