【问题标题】:rails active record traversing rowsrails 活动记录遍历行
【发布时间】:2011-11-20 10:17:40
【问题描述】:

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

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    要获取第一行,您可以使用.first

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

    .last 的工作方式相同:

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

    要获取第 n 行,请使用带有从 0 开始的索引的 [],与任何其他数组一样

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

    【讨论】:

    • 谢谢,我已经尝试过了,结果返回为零。发现我的问题是我没有将对象保存回数据库。
    【解决方案2】:

    获得一组结果后,您可以使用 [] 方法引用单个行。

    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
    

    【讨论】:

    • 一旦获得所有结果,您知道如何将特定列的所有值打印到单个字符串吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-15
    • 2013-02-01
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多