Rails filtering array of objects by attribute value
Try :
This is fine :
@logos = @attachments.select { |attachment| attachment.file_type == 'logo' }
@images = @attachments.select { |attachment| attachment.file_type == 'image' }
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
If your attachments are
@attachments = Job.find(1).attachments
This will be array of attachment objects
Use select method to filter based on file_type.
@logos = @attachments.select { |attachment| attachment.file_type == 'logo' }
@images = @attachments.select { |attachment| attachment.file_type == 'image' }
This will not trigger any db query.