无法显示简单的has_one关联:nil的未定义方法:NilClass

时间:2013-01-12 19:48:12

标签: ruby-on-rails ruby-on-rails-3

如果这看似重复,我很抱歉,但我没有看到解释清楚的解决方案。我有一个简单的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

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是show stop,@ 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 %>

3 个答案:

答案 0 :(得分:0)

如果作者没有图书,@author.book将会返回nil,那么您继续致电nil.title,然后就会爆炸。

你需要防范这种情况。可能围绕相关代码的if语句:

<% if @author.book %>
  <%= @author.book.title %>
<% else %>
  (none)
<% end %>

答案 1 :(得分:0)

您尝试展示的作者似乎有一本零书。因此,当您执行@author.book.title时,您将收到错误,因为title不是nil上的方法:NilClass。

要解决此问题,您需要通过以下方式检查零标题:

@author.book.try(:title)

或者只是确保所有作者在被认为有效之前总是有一本书,将其添加到您的作者模型中:

validates :book_id, :presence => true

答案 2 :(得分:0)

Book为nil,因为它尚未分配给作者。

<%= @author.book.nil? ? link_to 'Add Book', path(@author) : @author.book.title %>

<%= @author.book.nil? ? 'No Titles available' : @author.book.title %>
相关问题