Browse the Ruby on Rails Community.

You are here: Forums Ask a Rails expert Retrieving latest record from ...

Replytotopic

Retrieving latest record from database

Posted in Forums : Ask a Rails expert

 
Profile

Authority 37
Posting Rating 3
Sign in to rate this post

hi,

I have three tables( users, investments, comments).

my reqirement is to display recent entered record from all the three tables.

 
0f9ed70a8696f9a3f2e15ea107f3006b

Authority 62
Posting Rating 0
Sign in to rate this post

You can use this:
User.all(:order => “id DESC”, :limit => 5)
And same on your other models.

 
Profile

Authority 50
Posting Rating 45
Sign in to rate this post

I would do it like that:
a = []
a << User.find(:first, :order =>”created_at DESC”)
a << Investment.find(:first, :order =>”created_at DESC”)
a << Comment.find(:first, :order =>”created_at DESC”)
a..sort {|a,b| a.created_at <=> b.created_at}.first

 
Profile

Authority 37
Posting Rating 3
Sign in to rate this post

Thanks guys for ur help….....

 
Profile

Authority 50
Posting Rating 0
Sign in to rate this post

If you just the last entry in the table, you can use this:

User.last
Investment.last
Comment.last

 
Profile

Authority 62
Posting Rating 0
Sign in to rate this post

Though User.last will work in most of the scenarios, but if you have any default_scope on your AR::Base, it will be considered while fetching the last record. Say if you have:

class User < ActiveRecord::Base
  default_scope :order => "login DESC" 
end

User.last will return last user sorted by login.

Replytotopic

Other Recent Topics

Ask a Rails expert : nested application ApplicationController get called intead of children::ApplicationController

Ask a Rails expert : Best way to structure a database for a large/static dataset

Ask a Rails expert : Ruby Developer (ROR) - Scottish based (Remote working from within the UK)

Ask a Rails expert : Above Ground Pool Supplies

Ask a Rails expert : How to get url params in observer or model in Rails 3.1

Ask a Rails expert : What can persuade you to hire Junior Ruby devs with significant PHP experience?

Ask a Rails expert : What industry value does the Ruby or Rails Certification currently have?

Ask a Rails expert : Louis Vuitton Damier Azur Canvas specially sale ( www.salecheaplouisvuitton.com )

Ask a Rails expert : ·How to check errors/puts statements from ruby files which are under cronob

Ask a Rails expert : Louis Vuitton cheap Soft Sided Luggagespecial offer( www.salecheaplouisvuitton.com )

Formatting Help
  • *bold*       _italics_      
    bq. (quotes)
  • "DSC":http://www.dsc.net
  • * or # (lists)
or cancel