1

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

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

flatten is because he's doing to_a on Apple.where, resulting in an array of arrays. It's not as effective as other solutions.
0

You might add "all" at the end:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.