2

如何遍历 Activerecord::Relation 对象数组?例如,假设我有一个Comment班级和一个User班级,我想从 3 个特定用户那里获取所有评论内容(假设评论属于用户,user_id 是外键):

>> @males = Comment.where('user_id IN (?)', ["123","456","789"])
=> [...] #Array of comment Activerecord::Relation objects

现在我想遍历comments_from_males并收集content数组中每个评论的所有属性内容。

为了澄清,以下工作但仅适用于第一个男性返回,但我需要所有男性的所有评论:

>> @males.first.comments.map(&:content)
=> ["first comment", "second comment"]
4

3 回答 3

7
comments = @males.map {|user| user.comments.map(&:content)}.flatten
于 2012-09-17T16:22:20.043 回答
1

You can use

comments_from_males = @males.collect{|e| e.content if e.gender == "male"}.flatten

It will give you list of all comments from males. Check my db assumptions match.

于 2012-09-17T16:21:53.253 回答
1
Comment.where('user_id IN (?)', ["123","456","789"]).pluck(:content)

方法采摘

于 2012-09-17T16:31:57.027 回答