如果这看起来像重复,我深表歉意,但我没有看到明确解释的解决方案。我有一个简单的 has_one, belongs_to 关联
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
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
这个 Show.html.erb 是表演的终结者,@author.book.title 给了我一个 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 %>