activerecord - 按属性值过滤对象数组

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

@attachments = Job.find(1).attachments

现在我有一个对象数组,我不想执行另一个数据库查询,但我想基于Attachment对象的file_type过滤数组,这样我就可以得到attachments的列表,其中文件类型是'logo'然后 另一个列表attachments,其中的文件类型为'image'

像这样的东西:

@logos  = @attachments.where("file_type = ?", 'logo')
@images = @attachments.where("file_type = ?", 'image')

但是在内存中而不是db查询。

joepour asked 2019-09-10T11:05:56Z
4个解决方案
159 votes

试试:

这可以 :

@logos = @attachments.select { |attachment| attachment.file_type == 'logo' }
@images = @attachments.select { |attachment| attachment.file_type == 'image' }

但是对于性能方面,你不需要迭代@attachments两次:

@logos , @images = [], []
@attachments.each do |attachment|
  @logos << attachment if attachment.file_type == 'logo'
  @images << attachment if attachment.file_type == 'image'
end
Vik answered 2019-09-10T11:06:27Z
7 votes

如果您的附件是

@attachments = Job.find(1).attachments

这将是附件对象的数组

使用select方法根据file_type进行过滤。

@logos = @attachments.select { |attachment| attachment.file_type == 'logo' }
@images = @attachments.select { |attachment| attachment.file_type == 'image' }

这不会触发任何数据库查询。

Soundar Rathinasamy answered 2019-09-10T11:07:11Z
2 votes

你试过加载吗?

@attachments = Job.includes(:attachments).find(1).attachments
Siwei Shen 申思维 answered 2019-09-10T11:07:36Z
0 votes

您可以使用where过滤

Job.includes(:attachments).where(file_type: ["logo", "image"])
Darlan Dieterich answered 2019-09-10T11:08:02Z
translate from https://stackoverflow.com:/questions/10069993/rails-filtering-array-of-objects-by-attribute-value