I apologize if this may seem like a duplicate but I have not seen a solution explained clearly. I have a simple has_one, belongs_to association
class Author < ActiveRecord::Base
attr_accessible :name, :book_attributes
has_one :book
accepts_nested_attributes_for :book, :allow_destroy => true
end
class Book < ActiveRecord::Base
attr_accessible :title, :author_id
belongs_to :author
end
The authors_controller
class AuthorsController < ApplicationController
def index
@authors = Author.includes(:book).all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @authors }
end
end
def show
@author = Author.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @author }
end
end
def new
@author = Author.new
@book = @author.build_book
respond_to do |format|
format.html # new.html.erb
format.json { render json: @author }
end
end
This Show.html.erb is the show stopper, the @author.book.title is giving me a undefined method for nil:NilClass:
<p id="notice"><%= notice %></p>
<p>
<b>Name:</b>
<%= @author.name %>
</p>
<p>
<b>Book:</b>
<%= @author.book.title %><br/>
</p>
<%= link_to 'Edit', edit_author_path(@author) %> |
<%= link_to 'Back', authors_path %>
It appears the Author you’re trying to show has a nil Book. So when you do
@author.book.title, you’ll get the error sincetitleis not a method on nil:NilClass.To fix this, you’ll either need to check for a nil title by:
Or just make sure all authors always have a book before they’re considered valid by adding this to your Author model: