Find the newest record in Rails 3

后端 未结 5 611
眼角桃花
眼角桃花 2020-12-03 09:45

I was wondering if theres a way to find the newest record in a table in rails3?

Thanks

Elliot

5条回答
  •  被撕碎了的回忆
    2020-12-03 10:03

    While dmarkow's answer is technically correct, you'll need to make an index on created_at or risk an increasingly slow query as your database grows.

    If you know that your "id" column is an auto-increment primary key (which it likely is), then just use it since it is an index by definition.

    Also, unless AREL is optimized to select only one record in a find(:last), you run the risk of making it select ALL records, then return you just the last one by using the "last()" method. More efficient is to limit the results to one:

    MyModel.last(:order => "id asc", :limit => 1)
    

    or

    MyModel.first(:order => "id desc", :limit => 1)
    

提交回复
热议问题