Parent child query

I have two tables, lists and items. Each list can have multiple items.
I’m looking to output each list with its corresponding items, like so:

list 1
item 1
item 2
list 2
item 1
item 2
item 3
list 3
item 1

I’m having trouble figuring out how to do so. I can get the lists to
display, but I’m unsure on how to show the child items underneath each
list. I could query again from within the view, but that goes against
the MVC approach. I’m sure there’s an easy solution, I just can’t find
it.

do you mean something like?:

    <% @lists.each do |list| -%>
  • <%= list.name -%>
      <% list.items.each do |item| -%>
    • <%= item.name -%>
    • <% end -%>
  • <% end -%>

jdswift wrote:

do you mean something like?:

    <% @lists.each do |list| -%>
  • <%= list.name -%>
      <% list.items.each do |item| -%>
    • <%= item.name -%>
    • <% end -%>
  • <% end -%>

Yes, that’s what I’m looking to do, but how do I set it up in the
controller?

frank wrote:

Yes, that’s what I’m looking to do, but how do I set it up in the
controller?

first you need to define how both tables are connected in their Models

your list model will need s.th. like
has_many :items

and your items model
belongs_to :list

in the controller you can then do a .find like this

@lists = List.find(:all, :include => :items)

the erb part from jdswift then goes to your view (or a helper method
maybe)