2

我不确定我是否正确地用了这个问题,但我试图弄清楚这行代码实际上做了什么:

@orderdata = Order.find(:all, :conditions => ["customer_ID = ?",@data])

这是我的 SQL 数据库中 Orders 表包含的内容:

订单

+-------+------------+-------------+
| id    | order_date | customer_ID |
+-------+------------+-------------+
| 12475 | 2008-09-01 | 522         |
| 12476 | 2008-09-01 | 311         |
| 12477 | 2008-09-01 | 567         |
| 12478 | 2008-09-01 | 587         |
| 12482 | 2008-09-01 | 124         |
| 12483 | 2008-09-01 | 315         |
| 12484 | 2008-09-02 | 256         |
| 12489 | 2008-09-02 | 311         |
| 12494 | 2008-09-04 | 315         |
| 12495 | 2008-09-04 | 256         |
| 12498 | 2008-09-05 | 522         |
| 12504 | 2008-09-06 | 522         |
+-------+------------+-------------+

所以再一次,我将添加代码行,这样您就不必向上滚动:

@orderdata = Order.find(:all, :conditions => ["customer_ID = ?",@data])

我读了一些关于 Ruby on Rails 对这个 .find() 函数所做的事情,我开始相信它返回了某种类型的数组,但不确定到底是什么。

@data 是文本字段 HTML 表单中的用户输入,它应该是客户编号。所以我相信这行代码正在创建一个名为@orderdata 的数组并填充它。它在Orders表中查找所有出现的 key customer_ID等于@data(用户输入的客户编号/id)。

我想我的问题本质上是:@orderdata 中会有什么?以及如何访问其中的值?

谢谢!

4

2 回答 2

2

首先,Model.find(:all, :conditions => ...)不推荐使用 using 。相反,您应该使用Model.all(:conditions =>...)

并且,回答你的问题。其中@orderdataArray包含与给定条件匹配的所有对象(在您的情况下为匹配的 Order 对象数组customer_ID = 'some_id'

您实际上可以通过打开 Rails 控制台自己回答这个问题,然后执行以下操作:

Order.find(:all, :conditions => ["customer_ID = ?",@data]).class

那么,您如何访问这些结果?好吧,就像您将访问任何 Ruby 数组一样。如果要遍历所有结果,可以执行以下操作:

@orderdata.each do |order|
 # Do whatever you want with a particular order.
end
于 2013-11-11T21:11:16.013 回答
1

这段代码:

@data = 12 # for the example
@orderdata = Order.find(:all, :conditions => ["customer_ID = ?", @data])

将构建一个 Order 对象数组以响应以下 SQL:

SELECT * FROM orders WHERE orders.customer_ID = 12;

要访问这个数组的值,你可以循环它,或者只选择第一个/最后一个:

@orderdata.first # returns the first Order object of the array ; nil if list is empty
@orderdata.last # returns the last Order object of the array ; nil if empty

# loop through each element of the array and display it's attribute "customer_ID" (Rails Console style):
@orderdata.each do |order|
  puts order.customer_ID
end

我建议您使用.where()方法而不是查找:

c_id = 12
Order.where(customer_id: c_id) # returns a list of Order having 12 as customer_id

该方法的有趣之处在于.where(),您可以将查询链化:

orders = Order.where(paid: false)
orders = orders.where(customer_id: c_id) if c_id.present? # add the conditions if c_id is defined
orders = orders.where(order_date: (Date.today-1.day..Date.today)) # returns all the orders where their order_date is between yesterday & today

与常规数组相同的方式,访问数组的第一个和最后一个元素:

orders = Order.where(paid: false)
orders.first # returns the first of the list
orders.last  # returns the last
于 2013-11-11T21:09:13.993 回答