Find the newest record in Rails 3

后端 未结 5 581
眼角桃花
眼角桃花 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 09:52

    you may run into ambiguity issues using created_at on a sufficiently high-traffic table.

    eg. try:

    INSERT INTO table (created_at) VALUES ( NOW() );
    INSERT INTO table (created_at) VALUES ( NOW() );
    

    ..has the potential to have the same created_at, which only has 1 second of resolution. a sort would return them in no particular order.

    you may be better off storing a microtime value and sorting on that.

    0 讨论(0)
  • 2020-12-03 09:54

    Yes, you can use the method .last

    So if your model is called Post then:

    >> Post.last
    => #<Post ...>
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-03 10:03

    Try, for a model named ModelName:

    record = ModelName.last
    
    0 讨论(0)
  • 2020-12-03 10:04

    Given a Post model, you could do @post = Post.order("created_at").last

    (The reason I didn't just do a @post = Post.last is because that always defaults to sort by your primary key (usually id). Most of the time this is fine, but I'm sure there's a scenario where that could cause problems (e.g. setting custom IDs on records, database changes which affect the primary key sequencing/autonumbering, etc.). Sorting by the created_at timestamp ensures you are really getting the most recent record).

    0 讨论(0)
提交回复
热议问题