Rails:将关联的一部分推送到数组中的优雅方式

时间:2012-07-22 19:37:48

标签: ruby-on-rails arrays json model associations

我有postauthor型号。

author has_many :posts

现在我有authorposts

是否有一种优雅的方式只将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}}。

1 个答案:

答案 0 :(得分:5)

使用pluck

author.posts.pluck(:title)

http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck

  

pluck(column_name)

     

此方法旨在通过a执行选择   单列作为直接SQL查询返回值为的数组   指定的列名称值与列具有相同的数据类型。