我做了第一个,想检查一下我是否正确?我也不知道怎么做2号 Ruby ORM 在“customers”和“orders”表中考虑以下两个活动记录定义。 orders表有一个外键“cust_key”,它引用了“customers”的主键,也称为“cust_key”。
Table:
customers-
cust_key
address
orders-
order key
cust_key
order_priority
total_price
1 class Customer < ActiveRecord::Base
2 set_table_name "customers"
3 set_primary_key "cust_key"
4 has_many :orders, :foreign_key => "cust_key”
5 End
1 class Order < ActiveRecord::Base
2 set_table_name "orders"
3 belongs_to :customer, :foreign_key => "cust_key"
4 set_primary_key "order_key”
5 end
Consider the following piece of Ruby-on-Rails code.
1 <table>
2 <% Customers.all.each.do |c| %>
3 <tr>
4 <td><%= c.address %></td>
5 <td><%= c.orders.count() %></td>
6 </tr>
7 <% end %>
8 </table>
问题:
2个查询
SELECT FROM FROM customers
SELECT COUNT(*) FROM orders where orders.cust_key= customers.cust_key;
答案 0 :(得分:0)
我知道这是一个老问题,你可能已经忘记了它,但...... 如果你改变:
<% Customers.all.each.do |c| %>
<tr>
<td><%= c.address %></td>
<td><%= c.orders.count() %></td>
</tr>
<% end %>
到
<% Customers.includes(:orders).each.do |c| %>
<tr>
<td><%= c.address %></td>
<td><%= c.orders.length %></td>
</tr>
<% end %>
您将在一次SQL调用中显示客户信息。
包含方法,更改请求以使其使用带连接的单个查询,以便为所有客户收集相应的订单记录
请注意,我使用的是length而不是count,因为count将为每个customer(c)对象调用SQL计数,而length将查看已在第一次SQL调用中收集的订单数据的长度。 / p>