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 true.

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

Colin

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

@Bs=Array.new @As.each do |a|   @Bs<<B.where(a_id: a, is_visible: true) end

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 guides.rubyonrails.org. It’s possible to do things like:

class Blog < ActiveRecord::Base

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

end

class Post < ActiveRecord::Base

belongs_to :blog

end

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

@too_many_posts = @blogs.map(&:posts)

–Matt Jones