【发布时间】: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>
问题:
- 提供执行这段 Ruby-on-Rails 的 SQL 查询。总共将执行多少条 SQL 查询?
2 个查询
从客户中选择地址
SELECT COUNT(*) FROM orders where orders.cust_key= customers.cust_key;
- 编写一个 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