根据属性值Rails的对象过滤数组数组、属性、根据、对象

2023-09-08 18:52:40 作者:高贵冷艳女王范

所以,我执行查询的数据库,我有对象的完整的数组:

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
 
精彩推荐
图片推荐