【发布时间】:2011-11-20 10:17:40
【问题描述】:
我正在使用 .where() 方法访问数据库表。这应该返回很多行。如何查看第一行或第二行。我知道我可以使用 .each 方法遍历所有行,但如果我只想访问某一行怎么办。我是 Rails 新手,很抱歉这个简单的问题。
【问题讨论】:
标签: ruby-on-rails activerecord
我正在使用 .where() 方法访问数据库表。这应该返回很多行。如何查看第一行或第二行。我知道我可以使用 .each 方法遍历所有行,但如果我只想访问某一行怎么办。我是 Rails 新手,很抱歉这个简单的问题。
【问题讨论】:
标签: ruby-on-rails activerecord
要获取第一行,您可以使用.first
Model.where(:state => "active").first
.last 的工作方式相同:
Model.where(:state => "active").last
要获取第 n 行,请使用带有从 0 开始的索引的 [],与任何其他数组一样
Model.where(:state => "active")[1] #second result
【讨论】:
获得一组结果后,您可以使用 [] 方法引用单个行。
http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-5B-5D
results = YourClass.where(:foo => 'bar').all
results[0] # the first result
results[1] # the 2nd
# and so on until
results[results.length - 1] # the last item in the array
results[results.length] # out of bounds, and returns nil
# you can also use negative numbers to count backwards
results[-1] # the last element
results[-2] # the 2nd from last
【讨论】: