I’m a newbie in rails, and I’ve been looking all over for an answer for this issue. Here’s what I have:
class Item < ActiveRecord::Base
belongs_to :book
class Book < ActiveRecord::Base
has_many :items
Now I want to list all the items with their properties and the book associated with them. They would go under index in the items_controller.rb
class ItemsController < ApplicationController
# GET /items
# GET /items.xml
def index
@items = Item.all
now how would I handle books in the ItemsController so I can list them in index.html.erb keeping in mind that an item belongs to only one book? if I add:
@books = items.book.find
right under @items = Item.all so I can reference them in the index.html.erb I get:
undefined method ‘book’ for #<Array:0x10427f998>
I have a feeling that the answer is so simple but so far I haven’t figured it out. Is there any tutorial that you guys are aware of that covers this matter?
Thank you!
In your view, when you iterate over all of your
@items, just reference the book for each one. Example ERB (app/views/items/index.html.erb):If instead your intention is to display each book with the associated items under each book, you’d be better off using the
indexaction on theBooksController. Find all the books, iterate over each book, and for each book, iterate over the items for that book.