views:

92

answers:

2

What I want to do is something like this:

searchid = 4

while searchid != -1

  @a += A.find(searchid)
  @b = B.find(searchid)
  searchid = @b.parentid
end

The problem being the line

@a += A.find(searchid) 

The error being something like

NoMethodError: undefined method `+' for #<A:0x173f9a0>

So, how do you combine multiple 'find' requests?

A: 

You have to initialize @a = [] as an array before the += .

searchid = 4
@a = []
while searchid != -1

  @a += A.find(searchid)
  @b = B.find(searchid)
  searchid = @b.parentid
end

You can combine them like:

searchid = 4
@a = []
while searchid != -1

  @a += A.find(searchid)
  @a += B.find(searchid)
  searchid = @a.last.parentid
end
dombesz
Unfortunately that doesn't work.The error I get is: "TypeError: can't convert A into Array from (irb):8:in `+'"The 'A' being a model and the result of the 'find' being the result from a query to a database.I'm presuming you would need to create your own '+' function but I don't even know what format the find returns and I was hoping there was a more elegant solution.
peppermonkey
A: 

Got it to work (with help). Did the following:

@a = []

with

@a << A.find_by_something(something)

seems to have worked. Also using @a.compact! to get rid of the null entries.

Thanks for all the help :)

peppermonkey
Yep, i just saw that you receive only one element.
dombesz
Also if you have to mix up, for example you will receive both single elements and arrays, you can also use the << operator and you have to apply @a.flatten! to have still an array of elements instead of array with arrays.
dombesz