根据属性值Rails的对象过滤数组 [英] Rails filtering array of objects by attribute value
本文介绍了根据属性值Rails的对象过滤数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以,我执行查询的数据库,我有对象的完整的数组:
So I perform a query to the db and I have a complete array of objects:
@attachments = Job.find(1).attachments
现在,我有对象,我不希望执行另一个数据库查询的数组,但我想过滤的基础上附件
对象的<$数组C $ C> FILE_TYPE ,这样我可以有附件列表
其中,文件类型为标志
键,然后附件另一个列表
其中,文件类型为图像
Now that I have an array of objects I don't want to perform another db query, but I would like to filter the array based on the Attachment
object's file_type
so that I can have a list of attachments
where the file type is 'logo'
and then another list of attachments
where the file type is 'image'
事情是这样的:
@logos = @attachments.where("file_type = ?", 'logo')
@images = @attachments.where("file_type = ?", 'image')
但在内存中,而不是一个数据库查询。
But in memory instead of a db query.
干杯
推荐答案
尝试:
这是罚款:
@logos = @attachments.select { |attachment| attachment.file_type == 'logo' }
@images = @attachments.select { |attachment| attachment.file_type == 'image' }
但性能明智的,你不需要重复两次@attachments:
but for performance wise you don't need to iterate @attachments twice :
@logos , @images = [], []
@attachments.each do |attachment|
@logos << attachment if attachment.file_type == 'logo'
@images << attachment if attachment.file_type == 'image'
end
这篇关于根据属性值Rails的对象过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文