3

I have a simple association like:

class User < ActiveRecord::Base
   has_many :photos
end

class Photo < ActiveRecord::Base
   belongs_to :user

   # Photo fields => id, image, photo_type
end

In the photo model photo_type value can be in 'personal', family' or 'official'.

What is the best way to get all users either have NO photos OR photo_type != 'personal'(if the user has photos)?

I'd appreciate any help. Thanks!

Rakesh Patidar
  • 176
  • 1
  • 10

1 Answers1

2

I've flagged a duplicate which has lots of answers, but in a nutshell, you could use:

# No photos
User.includes(:photos).where( photos: { user_id: nil } )
# Not personal
User.includes(:photos).where.not( photos: { photo_type: "personal" } )

# Users with photos, where the `photo_type` isn't "personal"
User.includes(:photos).where.not( photos: { user_id: nil, photo_type: "personal" } )

There's also a Rails 5 approach that avoids loading the association, though I've not used yet personally:

User.left_outer_joins(:photos).where.not( photos: { user_id: nil, photo_type: "personal" } )

How does that look? The last option do what you're after?

Let me know if you've any questions.

SRack
  • 11,495
  • 5
  • 47
  • 60