Ruby on rails Rails关联不起作用(正如我预期的那样)
刚接触Rails并尝试测试我的关联。我有三个相互关联的模型:动物模型、秩序模型和线条模型。基本上,线条属于动物的目。我希望动物展示页面列出与该动物相关的所有订单,以及与该订单相关的行(目前为单数) 这是模型文件 animal.rb:Ruby on rails Rails关联不起作用(正如我预期的那样),ruby-on-rails,ruby-on-rails-3,activerecord,associations,models,Ruby On Rails,Ruby On Rails 3,Activerecord,Associations,Models,刚接触Rails并尝试测试我的关联。我有三个相互关联的模型:动物模型、秩序模型和线条模型。基本上,线条属于动物的目。我希望动物展示页面列出与该动物相关的所有订单,以及与该订单相关的行(目前为单数) 这是模型文件 animal.rb: class Animal < ActiveRecord::Base attr_accessible :breed, :photo, :animal_type has_many :orders end class Animal
class Animal < ActiveRecord::Base
attr_accessible :breed, :photo, :animal_type
has_many :orders
end
class Animal
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%>
但是,当我访问show页面时,会出现一个错误,即
undefined method `notes' for #<ActiveRecord::Relation:0x007f9259c5da80>
未定义的方法“notes”#
如果我删除了.notes,那么单位也是一样的。如果我同时删除这两行(并保留o.lines),页面将很好地加载,并在这两个表格单元格中列出相关行的所有信息(行id、行单位、行注释)。因此,它确实找到了正确的模型对象,但它不允许我调用特定属性
知道我做错了什么吗?难倒了。谢谢 在与订单关联的行集合上调用方法“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 %>
查看您的订单类别:
class Order < ActiveRecord::Base
has_many :lines
end
类顺序
你的视线:
o.lines.notes
o.lines
当前是属于订单的一组行
正如@rossta在我键入此内容时发布的,您可以连接所有行的注释。酷。我从来没见过。地图法。其思想是,它基本上是列出每行的注释,并加上“.”?这是怎么回事?我是否可以在循环中交替执行另一个o.lines.each do | l |行,然后为每一行创建一个新的表格行(以适应我在短期内为每个订单添加更多行的需求)?-是的,您可以解析每个o.行并单独处理这些行!我真的没有想到这一点,因为目前的协会更多的是一个有很多的,但我做了很多,因为我正计划改变这一点。