【问题标题】:Rails Association not working (as I expect it to)Rails 协会不工作(如我所料)
【发布时间】:2012-09-22 19:25:25
【问题描述】:

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

这里是模型文件。

动物.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 %>

最后,这是订单列表助手

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

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord associations models


    【解决方案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 %>
    

    【讨论】:

    • 酷。我从未见过那种 .map 方法。这个想法是它基本上列出了每一行的注释,用“。”连接?这里的&是什么?我可以交替做另一个 o.lines.each 做 |l|在循环中,然后为每一行创建一个新的表格行(以适应我为每个订单添加更多行的情况)?
    • ruby-doc.org/core-1.9.3/Array.html#method-i-map - 是的,您可以解析每个 o.lines 并分别处理
    【解决方案2】:

    查看您的 Order 类:

    class Order < ActiveRecord::Base
       has_many :lines 
    end
    

    还有你的观点:

    o.lines.notes

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

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

    【讨论】:

    • 谢谢!真的没有想到这一点,因为当前的关联更像是 has_one,但我将其设为“has_many”,因为我打算改变它。
    猜你喜欢
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多