Rails按属性值过滤对象数组

joe*_*our 91 activerecord ruby-on-rails

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

@attachments = Job.find(1).attachments
Run Code Online (Sandbox Code Playgroud)

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

像这样的东西:

@logos  = @attachments.where("file_type = ?", 'logo')
@images = @attachments.where("file_type = ?", 'image')
Run Code Online (Sandbox Code Playgroud)

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

Vik*_*Vik 166

试试:

这可以 :

@logos = @attachments.select { |attachment| attachment.file_type == 'logo' }
@images = @attachments.select { |attachment| attachment.file_type == 'image' }
Run Code Online (Sandbox Code Playgroud)

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

@logos , @images = [], []
@attachments.each do |attachment|
  @logos << attachment if attachment.file_type == 'logo'
  @images << attachment if attachment.file_type == 'image'
end
Run Code Online (Sandbox Code Playgroud)

  • 由于@Vik的解决方案非常理想,我只想在二进制情况下添加它,您可以使用"分区"功能来使事情变得甜美.http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-partition (2认同)

Sou*_*amy 8

如果您的附件是

@attachments = Job.find(1).attachments
Run Code Online (Sandbox Code Playgroud)

这将是附件对象的数组

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

@logos = @attachments.select { |attachment| attachment.file_type == 'logo' }
@images = @attachments.select { |attachment| attachment.file_type == 'image' }
Run Code Online (Sandbox Code Playgroud)

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