2013-05-03 1 views
0

여기에 내가 한 많은 관계로 2 간단한 모델이 있습니다레일 :보기에서 상위 모델의 속성을 호출 하시겠습니까?

class Category < ActiveRecord::Base 
    attr_accessible :Name 
    has_many :items 

class Item < ActiveRecord::Base 
    attr_accessible :Category_id, :Name, :Price, :Description 
    belongs_to :category 

을하고 내가 좋아하는 항목에 대한 정보를 표시하려면보기를했습니다 : 그것은 작업의 권리

<table> 
    <tr> 
    <td class="field" style="width: 175px;"><b>Name:</b></td> 
    <td><%= @item.Name %></td> 
    </tr> 
    <tr> 
    <td class="field"><b>Price:</b></td> 
    <td><%= @item.Price%></td> 
    </tr> 
    <tr> 
    <td class="field"><b>Category: </b></td> 
    <td><%= Category.find(@item.Category_id).Name %></td> 
    </tr> 
    <tr> 
    <td class="field"><b>Description: </b></td> 
    <td><%= @item.Description %></td> 
    </tr> 
</table> 

의를. 하지만 여기에 나는 질문을했습니다. 클래스 Category의 속성을 호출하는 또 다른 방법이 있습니까? 시도했지만 작동하지 않은 @item.category.Name과 같은 것

답변

1

왜 낙타의 경우 특성이 있습니까? 그들을와 downcase이 변경이에

<tr> 
    <td class="field"><b>Category: </b></td> 
    <td><%= Category.find(@item.Category_id).Name %></td> 
    </tr> 

를 : 그것은 작동해야

<tr> 
    <td class="field"><b>Category: </b></td> 
    <td><%= item.category.name %></td> 
</tr> 

.

+0

여전히 작동하지 않습니다. 위의 '정의되지 않은 메소드'name 'for nil : NilClass'과 같은 오류가 있습니다. – WindzSoul

0

here에 설명 된 것처럼 nil 확인이 도움이 될 수 있습니다.

<tr> 
    <td class="field"><b>Category: </b></td> 
    <td><%= @item.category.name unless @item.category.nil? %></td> 
</tr>