[英]Rails: Elegant way to push parts of the association into an array
I've got a post
and an author
model. 我有一个
post
和一个author
模型。
author has_many :posts
Now I have an author
with several posts
现在我有一个
author
有几篇posts
Is there an elegant way to get only the posts'
titles
as an array, not the whole post
object? 是否有一种优雅的方法仅将
posts'
titles
作为数组而不是整个post
对象获取?
So, not just author.posts
but something like author.posts.only(:title)
to get an array of titles. 因此,不仅要获得
author.posts
还需要诸如author.posts.only(:title)
类的东西来获取标题数组。 Eg ['post1','post2','post3']
. 例如
['post1','post2','post3']
。
That .only(:title)
syntax is from the JSON module and doesn't work in this case but there might be something more elegant than iterating over the posts
and pushing the titles
into a new array. .only(:title)
语法来自JSON模块,在这种情况下不起作用,但是可能比遍历posts
并将titles
推入新数组更优雅。 Something that queries the DB like select titles from posts where author_id = 23
. 查询数据库的东西就像
select titles from posts where author_id = 23
。
? ?
Use pluck
使用
pluck
author.posts.pluck(:title)
http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck
pluck(column_name)
动物内脏(列)
This method is designed to perform select by a single column as direct SQL query Returns Array with values of the specified column name The values has same data type as column.
此方法旨在通过单个列执行选择,作为直接SQL查询。返回具有指定列名的值的Array。这些值具有与列相同的数据类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.