tvalent2
tvalent2

Reputation: 5009

Getting NoMethodError, undefined method for nil:NilClass

I'm a beginner and am trying to show tag names associated to books (through taggings) in my book index view. The problem is that for some reason I get undefined method "tags" for nil:NilClass when I run:

  <% for book in @books %>
  <div id="book">
    <div class="bookHeader">
      <h5 class="bookTitle"><%= link_to book.title, book %></h5>
    <div class="bookTags">
      <ul class="tags">
        <li>
          <% for tag in @book.tags %>
          <%= link_to @tag.name %>
          <% end %>
        </li>
      </ul>
    ...
  <% end %>

In the index file I have:

  def index
    @books = Book.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @books }
    end
  end

In console, it shows that I do have associated tags:

>> @book = Book.find(12)
>> @book.tags.count
>> 3

Now I'm wondering if I need to construct a statement for if the books have tags or something like that. Anyone have any ideas? If I need to provide more code let me know.

Upvotes: 1

Views: 1533

Answers (1)

Thiago Jackiw
Thiago Jackiw

Reputation: 799

The problem on your code is that you have <% for tag in @book.tags %>, which @book doesn't exist. What you need is <% for tag in book.tags %>.

Upvotes: 1

Related Questions