これが重複しているように見えるかもしれませんが、明確に説明された解決策を見たことがありません。私は単純な 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
作者_コントローラ
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 %>