如何遍历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"]发布于 2012-09-18 00:22:20
comments = @males.map {|user| user.comments.map(&:content)}.flatten发布于 2012-09-18 00:21:53
您可以使用
comments_from_males = @males.collect{|e| e.content if e.gender == "male"}.flatten它会给你所有男性评论的列表。检查我的数据库假设是否匹配。
发布于 2012-09-18 00:31:57
Comment.where('user_id IN (?)', ["123","456","789"]).pluck(:content)pluck方法
https://stackoverflow.com/questions/12463254
复制相似问题