【问题标题】:Ruby on rails convert to sql queryRuby on rails 转换为 sql 查询
【发布时间】:2012-12-14 20:52:08
【问题描述】:

我做了第一个,想检查我是否做对了?我也不知道怎么做 2 红宝石 ORM 考虑表“客户”和“订单”上的以下两个活动记录定义。 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>

问题:

  1. 提供执行这段 Ruby-on-Rails 的 SQL 查询。总共将执行多少条 SQL 查询?

2 个查询
从客户中选择地址

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

【问题讨论】:

  • 1) 在rails console 中,您可以在任何查询上调用.to_sql 以获取生成的SQL 查询(例如:Customer.where(last_purchase: 1.week.ago..Time.zone.now).to_sql。) 2) 在log/development.log 文件中您应该得到显示所有已执行的查询。您可以在控制台中使用 tail -f log/development.log 跟踪此文件。
  • 我是 ruby​​ 的新闻,甚至不知道如何运行它
  • 那么明智的做法是从不太具体的内容开始,例如这个简短的Getting started guide in the Rails guides,以便快速了解 Rails。
  • 您可以通过导航到应用程序文件夹并输入rails console 来调用终端中的rails 控制台。

标签: sql ruby-on-rails ruby database


【解决方案1】:

我知道这是一个老问题,你可能已经忘记了,但是...... 如果你改变:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 2012-06-10
    • 2012-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多