ChrisWesAllen
ChrisWesAllen

Reputation: 4975

Ruby/Rails - How can I add items to an object with each loop iteration

I'm trying to figure ruby out a bit more.....

If I have an object

 @Trees =  Tree.find( :all )

Then make a loop where for each tree I find, add some apples...

 for tree in @trees   
     @apples = Apple.where(:tree_location = > tree.id )
 end

How can I add the additional apples found from each iteration of the loop to the initial object @apples ?

I tried

    @apples = @apples + Apple.where(:tree_location = > tree.id )

but got the error "can't convert Apple into Array"

Thanks for the help .... i'm on a cider deadline lol, corny i know

Upvotes: 1

Views: 1780

Answers (3)

Gergõ Sulymosi
Gergõ Sulymosi

Reputation: 814

If you want all apples on all the trees, you should have a look at the following query:

@trees =  Tree.find( :all )
@apples = Apple.where(:tree_location => trees.map(&:id))

generates the following sql

select * from apples where tree_location in (... tree ids ...);

it will give you all the apples that belongs to the trees, and costs only two queries instead of n+1

Upvotes: 2

coder_tim
coder_tim

Reputation: 1720

You might add "all" at the end:

@apples = @apples + Apple.where(:tree_location = > tree.id ).all

Upvotes: 0

stef
stef

Reputation: 14268

Not quite sure I get you, but...

trees =  Tree.find( :all )
apples = []
trees.each do |tree|
  apples << Apple.where(:tree_location = > tree.id ).to_a
end

apples = apples.flatten.uniq!

puts apples.inspect

Upvotes: 0

Related Questions