Sim*_*ton 2 activerecord ruby-on-rails
如何遍历Activerecord :: Relation对象的数组?例如,假设我有一个Comment类和一个User类,我想从3个特定用户获取所有评论内容(假设评论属于用户,而user_id是外键):
>> @males = Comment.where('user_id IN (?)', ["123","456","789"])
=> [...] #Array of comment Activerecord::Relation objects
Run Code Online (Sandbox Code Playgroud)
现在我想迭代comments_from_males并收集content数组中每个注释的所有属性内容.
为了澄清,下面的工作,但只有第一个男性返回,但我需要所有男性的所有评论:
>> @males.first.comments.map(&:content)
=> ["first comment", "second comment"]
Run Code Online (Sandbox Code Playgroud)
comments = @males.map {|user| user.comments.map(&:content)}.flatten
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5717 次 |
| 最近记录: |