All threads / Grabbing all the has_many relations of a specific collection

Ask A Question

Notifications

You’re not receiving notifications from this thread.

Grabbing all the has_many relations of a specific collection

Chris Zempel asked in General

I've got:

class User < ActiveRecord::Base
  has_many :photos
end

class Photo < ActiveRecord::Base
  belongs_to :user
end

Each user has a "shadowbanned" attribute (t/f). I'd like to be able to grab all the photos where the users aren't shadowbanned.

How would you recommend I set up either the scope or the association to have Rails do the most work possible?

Guess what I'm asking is, is there anything cleaner than this:

    valid_photos = Photo.where.not(user_id: User.where(shadowbanned: true).pluck(:id))
Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 33,665+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.