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?

On 10 April 2014 22:20, Jan Yo [email protected] wrote:

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

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<<a.bs.select{ |b| b.is_visible}
end

El jueves, 10 de abril de 2014 23:20:53 UTC+2, Ruby-Forum.com User
escribió:

On Friday, 11 April 2014 07:13:25 UTC-4, Ruby-Forum.com User wrote:

@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 J.

B.where(a_id: @As)

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<<a.bs
end

El jueves, 10 de abril de 2014 23:20:53 UTC+2, Ruby-Forum.com User
escribió:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs