Chris F.
Chris F.

Reputation: 501

Rails Getting Started Question

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!

Upvotes: 1

Views: 890

Answers (3)

Ryan McGeary
Ryan McGeary

Reputation: 239914

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):

<% @items.each do |item| -%>
  Item: <%= item.name %>
  Book: <%= item.book.title %>
<% end -%>

If instead your intention is to display each book with the associated items under each book, you'd be better off using the index action on the BooksController. Find all the books, iterate over each book, and for each book, iterate over the items for that book.

Upvotes: 5

Kaleb Brasee
Kaleb Brasee

Reputation: 51945

The problem is that you're calling items.book on an array of items, and the array doesn't have a method named book (hence the error). You'd need to get a single book from that array (such as items[0]), then call .book on that.

Upvotes: 0

Brian Kelly
Brian Kelly

Reputation: 5664

The array of items doesn't have a book, each individual item does. It looks like you're trying to get the book of ALL the items, which doesn't exist.

Try @items[0].book or using a loop in your view:

<ul>
<% for item in @items %>
  <li><%= item.book.title %></li>
<% end %>
</ul>

You could also use a partial to iterate through the array. See the section "Rendering a collection of partials" at http://api.rubyonrails.org/classes/ActionView/Partials.html

Upvotes: 1

Related Questions