繁体   English   中英

Ruby on Rails转换为SQL查询

[英]Ruby on rails convert to sql query

我做了第一个,想检查我是否正确? 我也不知道该怎么做2 Ruby ORM考虑在表“ customers”和“ orders”上的以下两个活动记录定义。 订单表具有一个外键“ cust_key”,该外键引用了“客户”的主键,也称为“ 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>

问题:

  1. 提供执行此Ruby-on-Rails所产生的SQL查询。 总共将执行多少个SQL查询?

2查询
选择客户的地址

     SELECT COUNT(*) FROM orders where orders.cust_key= customers.cust_key;
  1. 编写一个仅发出一个SQL查询的jsp片段,并与上面的Ruby-on-Rails片段创建相同的html。

我知道这是一个古老的问题,您可能已经忘记了,但是...如果您进行更改:

<% 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调用中显示客户信息。

include方法更改请求,以便它使用带有联接的单个查询来收集所有客户及其相应的订单记录

请注意,我使用了长度而不是计数,因为count将为每个客户(c)对象调用一个SQL计数,而length将查看在第一个SQL调用中已经收集的订单数据的长度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM