0

Rails 新手并尝试测试我拥有的关联。我有这三个相互关联的模型:Animal、Order 和 Line。基本上,线条属于命令属于动物。我希望动物展示页面列出与该动物相关的所有订单以及与该订单相关的行(目前是单数)。

这是模型文件。

动物.rb:

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

线.rb

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

订单.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 %>

最后,这是订单列表助手

<% @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、行单位、行注释)。所以它肯定是找到了正确的模型对象,但它并没有让我调用特定的属性。

知道我做错了什么吗?难住了。谢谢!

4

2 回答 2

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 回答
1

查看您的 Order 类:

class Order < ActiveRecord::Base
   has_many :lines 
end

和你的观点:

o.lines.notes

o.lines当前是一组属于 Order 的行。

正如@rossta 在我输入此内容时发布的那样,您可以连接所有行的注释。

于 2012-09-22T19:32:11.947 回答