# Array within an array

**URL:** <https://www.ruby-forum.com/t/array-within-an-array/125336>\
**Category:** Rails\
**Created:** [January 8, 2008, 11:42am UTC](https://www.ruby-forum.com/t/array-within-an-array/125336 "2008-01-08T11:42:16Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![hiddenhippo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/65b543/32.png) [@hiddenhippo](https://www.ruby-forum.com/u/hiddenhippo)\
**Post date:** [January 8, 2008, 11:42am UTC](https://www.ruby-forum.com/t/array-within-an-array/125336/1 "2008-01-08T11:42:16Z")

</div>

Hi, hoping someone can help, or at least suggest a better way of  
doing the following.

I have two models which have a has\_and\_belongs\_to\_many relationship.  
for example products and items. On my page view I provide a selection  
list (collection\_select) of the products, and when the user changes  
the selection I fetch the items that are relevant to that product.  
However as part of optimising the code I’ve been using the following  
when assigning the products variable

@products =  
Product.find(:all, :include=\>[:items],:order=\>“products.description”)

I then bind the product dropdown with @products, and subject to what  
selection they make I need to pass the correct items to an item  
partial. I know this has to be done by effectively passing  
@products[0].items, but how do I figure out where in the array my  
original product is, e.g. :products[0] or @products[1]… at the  
moment I can only think of looping over the @products array looking  
for a matching id and when I’ve got that pass the items and break out  
of the loop. I’m pretty certain there must be a cleaner way rather  
than manually coding the loop?

Any ideas or suggestions would be greatly appreciated.

thanks

---

<div class="post-metadata">

**Author:** ![hiddenhippo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/65b543/32.png) [@hiddenhippo](https://www.ruby-forum.com/u/hiddenhippo)\
**Post date:** [January 9, 2008, 12:49am UTC](https://www.ruby-forum.com/t/array-within-an-array/125336/2 "2008-01-09T00:49:10Z")

</div>

Pass in the product\_id to the partial, without doing eager loading of  
the  
items.

@products = Product.find(:all, :order =\> “description”)

Then do a  
@product = Product.find(params[:id])  
@product.items

to get the items in the partial.

On Jan 8, 2008 9:11 PM, hiddenhippo [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> of the loop. I’m pretty certain there must be a cleaner way rather  
> than manually coding the loop?
> 
> Any ideas or suggestions would be greatly appreciated.
> 
> thanks
> 
> >

–  
Ryan B.

> **[frozenplague.net](http://www.frozenplague.net)**
>
> This domain may be for sale!

Feel free to add me to MSN and/or GTalk as this email.
