Forum: Ruby on Rails Getting 1 from children of has_many, Noob question...

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Lance S. (Guest)
on 2006-06-12 21:51
The 'Agile Web' book says that you can iterate over a list of children
as so:

order.line-items.each do |li|
etc...

This is fine when you need then all consecuitvely, but I need to pull
the first one for the top of the page and still list all at the bottom.

So, the question is:

How do I reference the first item (child) directly?

Thanks

Lance F. Squire
Chris T (Guest)
on 2006-06-12 22:10
(Received via mailing list)
Not tested, but something like...

order.line-items.first # for the first one


(order.line-items - order.line-items.first).each do # for the remaining
ones

Tho' would be better to define the first one and remaining ones in the
controller;

@first_line-item = order.line-items.first

@remaining_line-items = order.line-items - order.line-items.first


HTH
Lance S. (Guest)
on 2006-06-12 23:48
Chris T wrote:
> Not tested, but something like...
>
> order.line-items.first # for the first one
>
>

Thanks! This worked well.

Had to change it to something like:

order.line-items.first.unit_price

to get what I wanted.

Needed compleate list at bottom, so extra code not need but good for
future reference.

Thanks,

Lance
This topic is locked and can not be replied to.