所以,我执行查询的数据库,我有对象的完整的数组:
So I perform a query to the db and I have a complete array of objects:
@attachments = Job.find(1).attachments
现在,我有对象,我不希望执行另一个数据库查询的数组,但我想过滤的基础上附件
对象的 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