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)
如果您的附件是
@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)
这不会触发任何数据库查询.
归档时间: |
|
查看次数: |
90686 次 |
最近记录: |