Iterate over a set of classes

I have class A and B. A has many Bs.
B has a field is_visible which can be true or false
I have alot of As as well

I can acquire a set of As by doing the follwoing:

@As = X.find_by...

Need to iterate over all the As, and return each B where B.is_visble is

since we are going across all As, I would think the final result would
be @Bs (notice s at end).

Best way to do this?

Do you mean that you just want all Bs where is_visible is true? If so
then what is wrong with
B.where is_visible: true


Ups i forget the visible condition

B.where(a_id: @As, is_visible: true)

if you have a massive amounts of Bs the Data Base server will hate
you,so a better solution is
@As.each do |a|
  @Bs<<B.where(a_id: a, is_visible: true)

If you have “massive amounts” of B records, the DB server won’t be the bottleneck - instantiating all those objects will be. Doing more SQL queries is usually the opposite of optimization.

I’d also recommend you check out the associations guide on It’s possible to do things like:

class Blog < ActiveRecord::Base

has_many :visible_posts, -> { where(is_visible: true) }, class_name: ‘Post’


class Post < ActiveRecord::Base

belongs_to :blog


@blogs = Blog.includes(:visible_posts).find_by_whatever(…)

@too_many_posts =

–Matt Jones