这个奇怪的错误需要一些帮助:得到2个类:

class Avatar < ActiveRecord::Base

  belongs_to :avatarable, :polymorphic => true
  attr_accessible :photo_content_type, :photo_file_name, :photo_file_size, :photo

class Group < ActiveRecord::Base
  include ActiveModel::Validations
  attr_accessible :location_attributes, :image_attributes, :name,
                   :location_id, :location_name, :scribble_attributes, 
                   :group_type, :privacy, :about, :membership_id, :event_id, :headline,   :avatar_attributes


  has_one :avatar, :as => :avatarable, :dependent => :destroy
  accepts_nested_attributes_for :avatar

这是一个show.html,如果存在,应该显示头像 .

<% @groups.each do |g|%>
<h5>Name </h5>
<%=link_to g.name, group_path(g.id) %> <br>
<%if !g.avatar.nil?%> **also tried (g.avatar.photo.exists?)*(g.avatar.present?) (g.avatar.exists?)**
<li> <%= link_to image_tag(g.avatar.photo.url(:thumb)), group_path(g.id) %> </li> 
<%else%>
<li> <%= link_to image_tag(g.avatar.photo.url(:default_url)), group_path(g.id) %> </li> 
<%end%>
<%end%>

如果组没有头像我会一直收到错误 - undefined method for nil:NilClass

如果我想在初始化或after_save上做@ Group.build_avatar之类的事情,或者在任何检查之前我得到 STACK LEVEL TOO DEEP ERROR

activerecord(3.2.13)lib / active_record / associations / association.rb:61

undefined method `photo' for nil:NilClass

app / views / groups / _groupsresults.html.erb:11:在 block in _app_views_groups__groupsresults_html_erb___226577206_56390436' app/views/groups/_groupsresults.html.erb:3:in 每个'app / views / groups / _groupsresults.html.erb:3:in _app_views_groups__groupsresults_html_erb___226577206_56390436' app/views/groups/index.html.erb:14:in _app_views_groups_index_html_erb___393629073_55205484'请帮忙,这真是令人沮丧; /