Ruby on rails从结果集中获取最后一条记录

时间:2013-03-14 13:24:35

标签: sql ruby-on-rails record

@connection = ActiveRecord::Base.establish_connection(
            :adapter => "mysql2",
            :host => "localhost",
            :database => "siteconfig_development",
            :username => "root",
            :password => "root123"
)

sql = 'SELECT * from users'

@success_data = @connection.connection.execute(sql);

如何从@success_data获取最后一条记录而不进行迭代?

3 个答案:

答案 0 :(得分:1)

sql ='SELECT * from users order by id desc limit 1'

答案 1 :(得分:1)

<强>更新

  @success_data = @connection.connection.select_all(sql);
  @success_data.class  
  => Array

您可以在@success_data

上使用任何数组方法
  @success_data.last  # will return the last element   

  @success_data[-1]   # will return the last element

答案 2 :(得分:0)

你可以对集合做.last但是你在这里做的有点偏离轨道路径,这是你访问数据库的默认方式还是一个特例?