views:

35

answers:

1

I have two complex rails (AR) queries coming from two different methods that I sometimes want to concatenate. The data structure returned in each object is the same I just want to append one onto another.

Here's a simplified example (not my actual code):

 @peep1 = Person.find(1)

 @peep2 = Person.find(2)

Thought something like this would work:

 @peeps = @peep1 << @peep2

or this

 @peeps = @peep1 + @peep2

The above is just a simplified example - joining the queries etc won't work in my case.

Edit: Maybe concatenating is the wrong term.

Here's the output I'd like:

Say @peep1 has:
first_name: Bob
last_name: Smith

and @peep2 has:
first_name: Joe
last_name: Johnson

I want these to be combined into a third object. So if I iterate through @peeps it will contain the data from both previous objects:

@peeps has:
first_name: Bob
last_name: Smith
first_name: Joe
last_name: Johnson

Thanks!

+4  A: 

To be frank, nothing that you are describing makes any sense :)

@peep1 and @peep2 each represent a single object -- a single row in the database.

There is no sense in which they can be meaningfully combined.

You can make an array of both of them.

@all_peeps = [@peep1, @peep2]

And then iterate over that.

@all_peeps.each do |peep|
  print peep.first_name
end
John
"nothing that you are describing makes any sense" - guess you read my mind then :). thanks
bandhunt