Rails 按属性值过滤对象数组 [英] Rails filtering array of objects by attribute value

查看:29
本文介绍了Rails 按属性值过滤对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I perform a query to the db and I have a complete array of objects:

@attachments = Job.find(1).attachments

现在我有一个对象数组,我不想执行另一个 db 查询,但我想根据 Attachment 对象的 file_type 过滤数组这样我就可以有一个文件类型为 'logo'attachments 列表,然后是另一个文件类型为 attachments 的列表代码>'图像'

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆