0

Rails에 처음 오르고 내가 가진 연관성을 테스트하려고합니다. 동물, 주문 및 선의 3 가지 상호 연관된 모델이 있습니다. 기본적으로 라인은 동물에 속하는 주문에 속합니다. 동물 쇼 페이지에 해당 동물과 관련된 모든 주문과 그 주문과 관련된 라인 (단, 현재는 해당)을 나열하고 싶습니다.Rails Association이 작동하지 않습니다 (예상대로)

다음은 모델 파일입니다.

animal.rb :

class Animal < ActiveRecord::Base 
    attr_accessible :breed, :photo, :animal_type 
    has_many :orders 
end 

line.rb

class Line < ActiveRecord::Base 
    belongs_to :order 
    attr_accessible :notes, :units 
end 

order.rb

class Order < ActiveRecord::Base 
    belongs_to :animal 
    attr_accessible :status, :lines_attributes, :animal_id 

    has_many :lines 

    accepts_nested_attributes_for :lines 
end 

내가 관련된 모든 라인과 주문을 표시한다 할 노력하고있어 동물 쇼보기에서 주어진 동물. 여기

undefined method `notes' for #<ActiveRecord::Relation:0x007f9259c5da80> 

말을 마지막으로, 여기에 orderlist 도우미

<% @animal.orders.each do |o| %> 
    <tr> 
     <th><%= o.id %></th> 
     <th><%= o.status %></th> 
     <th><%= o.lines.notes %></th> 
     <th><%= o.lines.units %></th> 
    </tr> 
<%end%> 

그래도, 쇼 페이지를 방문 할 때이 오류를 던졌습니다입니다, 내 공연보기

<p id="notice"><%= notice %></p> 

<div class="pull-left"> 
    <h2><span style="font-size:80%"> Animal Name: </span><%= @animal.name %></h2> 
</div> 

<br> 
<table class="table"> 
    <tr> 
    <th>Type of Animal</th> 
    <th>Breed</th> 
    <th>Photo</th> 
    </tr> 
    <tr> 
    <td><%= @animal.animal_type %></td> 
    <td><%= @animal.breed %></td> 
    <td><%= @animal.photo %></td> 
    </tr> 
</table> 

<br> 
<h2>Associated Orders</h2> 
<table class="table"> 
    <tr> 
    <th>Order Number</th> 
    <th>Order Status</th> 
    <th>Line Notes</th> 
    <th>Line Units</th> 
    <tr> 
    <%= render 'orderlist' %> 
</table> 

<br> 

<%= link_to 'Edit', edit_animal_path(@animal) %> | 
<%= link_to 'Back', animals_path %> 

입니다 그리고 만약 .notes를 지우면, 단위에 대해서도 같은 것을 말합니다. 둘 다 삭제하고 o.lines를 남겨두면 페이지가 잘로드되어 해당 두 줄의 표 셀에 관련 줄의 모든 정보 (줄 ID, 줄 단위, 줄 수)가 나열됩니다. 따라서 올바른 모델 객체를 확실히 찾을 수는 있지만 특정 속성을 호출하지는 않습니다.

내가 뭘 잘못하고 있는지 아는 사람이 있습니까? 엉망진창. 감사!

답변

1

컬렉션의 행의 "메모"및 (단위 ")를 호출하고 있습니다. 순서에서 각 행에 대해 해당 메소드를 호출 할 수 있습니다. 출력하려면 뷰의 각 행에 대한 메모, 거친 재 작성 될 수있다 : 당신의 주문 클래스에서

<% @animal.orders.each do |o| %> 
    <tr> 
    <th><%= o.id %></th> 
    <th><%= o.status %></th> 
    <th><%= o.lines.map(&:notes).join('. ') %></th> 
    <th><%= o.lines.map(&:units).join('. ') %></th> 
    </tr> 
<% end %> 
+0

차가움. 나는 그 .map 메소드를 본 적이 없다. 아이디어는 기본적으로 "."로 합쳐진 각 줄의 노트를 나열하는 것입니다. 여기에 &에 대해 무엇입니까? 교대로 또 다른 일을 할 수 있을까요? lines.each do | l | 루프 내에서 다음 각 줄에 대한 새 테이블 줄을 만듭니다 (곧 내 주문 당 더 많은 줄 추가) 수용 할 수 있습니까? – Sasha

+0

http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-map - 예. 각 o.lines를 구문 분석하고 개별적으로 처리 할 수 ​​있습니다. –

1

봐 :

class Order < ActiveRecord::Base 
    has_many :lines 
end 

그리고보기 라인 :

o.lines.notes

o.lines은 현재 주문에 속한 일련의 줄입니다.

내가 입력하는 동안 @rossta가 게시 했으므로 모든 줄에 표시된 내용을 연결할 수 있습니다.

+0

고마워요! 생각하지 않았어요, 현재 협회가 has_one의 이상 이었기 때문에, 나는 그것을 변화시킬 계획 이었기 때문에 "has_many"로 만들었습니다. – Sasha

관련 문제