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
开发者_StackOverflow @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
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
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
You might add "all" at the end:
@apples = @apples + Apple.where(:tree_location = > tree.id ).all
精彩评论