I have did the first one, and want to check if I got it right or not? also I have no idea how to do number 2 Ruby ORM Consider the following two active record definitions over the tables “customers” and “orders”. The orders table has a foreign key “cust_key” that references the primary key of “customers”, which is also named “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>
Questions:
2 queries
SELECT address FROM customers
SELECT COUNT(*) FROM orders where orders.cust_key= customers.cust_key;
I know that this is an old question, and you've probably forgotten it but ... If you change:
<% Customers.all.each.do |c| %>
<tr>
<td><%= c.address %></td>
<td><%= c.orders.count() %></td>
</tr>
<% end %>
to
<% Customers.includes(:orders).each.do |c| %>
<tr>
<td><%= c.address %></td>
<td><%= c.orders.length %></td>
</tr>
<% end %>
You'll display the customer information in one SQL call.
The includes method, changes the request so that it uses a single query with a join, to gather all customers with their corresponding order records
Note that I've used length rather than count, as count will call a SQL count for each customer (c) object, whereas length will look at the length of orders data already gathered in the first SQL call.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.