2012-01-23 2 views
0

그래서 나는 라이언 베이츠 Simple_Form railscast으로 장난하고있어, 나는 양식을 제출하려고 할 때 다음과 같은 오류가 :정의되지 않은 방법 '호출'NilClass

NoMethodError in Products#index 

Showing /home/panos/sites/store/app/views/products/index.html.erb where line #8 raised: 

undefined method `name' for nil:NilClass 
Extracted source (around line #8): 

5:  <h2><%= link_to product.name, product %></h2> 
6:  <div> 
7:  Price: <%= number_to_currency product.price %><br /> 
8:  Category: <%= product.category.name %><br /> 
9:  <%= link_to "Edit", [:edit, product] %> 
10:  </div> 
11: <% end %> 
Rails.root: /home/panos/sites/store 

Application Trace | Framework Trace | Full Trace 
app/views/products/index.html.erb:8:in `block in _app_views_products_index_html_erb___762171406_75615480_549568821' 
app/views/products/index.html.erb:4:in `each' 
app/views/products/index.html.erb:4:in `_app_views_products_index_html_erb___762171406_75615480_549568821' 

것은 여기 내 인덱스입니다. html.erb 파일 : 나는 알고

<%= simple_form_for @product do |f| %> 
    <%= f.error_messages %> 
    <table border="1"> 
    <tr> 
    <td><%= f.input :name %></td> 
    <td><%= f.input :price, :hint => "prices should be in USD" %></td> 
    <td><%= f.input :released_on %></td> 
    <td> <%= f.association :category, :include_blank => false %></td> 
    <td><%= f.input :rating, :collection => 1..5, :as => :radio %></td> 
    <td><%= f.input :discontinued %></td> 
    <td><%= f.button :submit %></td> 
    </tr> 

<% end %> 

: 여기

<% title "Products" %> 

<div class="product"> 
    <% for product in @products %> 
    <h2><%= link_to product.name, product %></h2> 
    <div> 
     Price: <%= number_to_currency product.price %><br /> 
     Category: <%= product.category.name %><br /> 
     <%= link_to "Edit", [:edit, product] %> 
    </div> 
    <% end %> 
</div> 

<p><%= link_to "New Product", new_product_path %></p> 

그리고 내 form.html.erb 파일입니다 범주 필드 (nill) 비어 있기 때문에 오류가 생성됩니다,하지만 nill 값으로 표시 할 수 있도록 그것을 수정하는 방법을 모릅니다.

아무도 도와 줄 수 있습니까?

답변

2

이 시도 :

Category: <%= product.category.name unless product.category.nil? %> 
3

또는 조금 더 간결하게.

Category: <%= product.category.name if product.category %> 또는 try 방법은 사람들이 많이 의해 눈살을 찌푸렸다 있지만

Category: <%= product.category.try(:name) %>

.

0

최소한 하나의 행에 대해 product.category의 값이 nil이므로 product.category가 'name'에 액세스하기 위해 참조 해제 될 때 예외가 발생합니다.

글을 쓰는 시점에 제공된 답변 중 '제외'솔루션은 nil 참조를 방지합니다. 'try'솔루션은 예외가 발생하는 경우 예외를 안전하게 캐치합니다.