0

Railsが初めてで、私が持っている関連付けをテストしようとしています。相互に関連する次の 3 つのモデルがあります。動物、秩序、線です。基本的に、ラインはオーダーに属し、アニマルに属します。そして、動物ショー ページに、その動物に関連付けられたすべての注文と、その注文に関連付けられた行 (今のところ単数) を一覧表示するようにします。

ここにモデルファイルがあります。

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

私がやろうとしているのは、アニマル ショー ビューで特定の動物に関連付けられているすべての行と注文を表示することです。これが私のショービューです

<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 %>

そして最後に、これがその 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%>

ただし、ショーページにアクセスすると、これによりエラーがスローされます。

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

.notes を削除すると、ユニットについても同じことが言えます。両方を削除 (および o.lines を残す) すると、ページが正常に読み込まれ、関連する行のすべての情報 (行 ID、行単位、行メモ) がこれら 2 つのテーブル セルに一覧表示されます。したがって、適切なモデル オブジェクトを確実に見つけていますが、特定の属性を呼び出すことはできません。

私が間違っていることは何か分かりますか?困惑した。ありがとう!

4

2 に答える 2

1

Order クラスを見てください。

class Order < ActiveRecord::Base
   has_many :lines 
end

そしてあなたのビューライン:

o.lines.notes

o.lines現在、注文に属する行のセットです。

これを入力している間に @rossta が投稿したように、すべての行のメモを連結できます。

于 2012-09-22T19:32:11.947 に答える
1

注文に関連付けられた明細行のコレクションに対して、メソッド「notes」(および「units」) を呼び出しています。注文の各行に対してこれらのメソッドを呼び出そうとするかもしれません。ビューの各行のメモを出力するには、大まかに書き直すと次のようになります。

<% @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 %>
于 2012-09-22T19:30:51.517 に答える