2011-11-20 79 views
2

我正在使用.where()方法访问数据库表。这应该返回许多行。我如何查看第一行或第二行。我知道我可以使用.each方法来遍历所有行,但如果我只想访问某一行,该怎么办?我是新来的铁路,所以很抱歉这个简单的问题。rails活动记录遍历行

回答

5

为了得到第一排,你可以用.first

Model.where(:state => "active").first 

.last的工作方式相同:

Model.where(:state => "active").last 

为了得到第n行,使用[]与基于0指数,如同任何其他阵列一样

Model.where(:state => "active")[1] #second result 
+0

谢谢,我是想已经和它返回nil。找出我的问题是我没有将对象保存回数据库。 – Keeto

1

一旦你有你的结果集可以用[]方法引用单个行。

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 
+0

一旦有了所有的结果,任何想法如何将一个特定列的所有值打印到单个字符串? – BKSpurgeon