Rails filtering array of objects by attribute value

前端 未结 5 2035
天涯浪人
天涯浪人 2020-12-12 13:33

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

@attachments = Job.find(1).attachments

Now that I have an array of o

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-12 14:10

    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
    

提交回复
热议问题