Rails filtering array of objects by attribute value

前端 未结 5 2027
天涯浪人
天涯浪人 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 13:47

    You can filter using where

    Job.includes(:attachments).where(file_type: ["logo", "image"])
    
    0 讨论(0)
  • 2020-12-12 13:50

    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.

    0 讨论(0)
  • 2020-12-12 13:57

    have you tried eager loading?

    @attachments = Job.includes(:attachments).find(1).attachments
    
    0 讨论(0)
  • 2020-12-12 14:07

    I'd go about this slightly differently. Structure your query to retrieve only what you need and split from there.

    So make your query the following:

    #                                vv or Job.find(1) vv
    attachments = Attachment.where(job_id: @job.id, file_type: ["logo", "image"])
    # or 
    Job.includes(:attachments).where(id: your_job_id, attachments: { file_type: ["logo", "image"] })
    

    And then partition the data:

    @logos, @images = attachments.partition { |attachment| attachment.file_type == "logo" }
    

    That will get the data you're after in a neat and efficient manner.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题