Jump to content

The ultimate community for Ruby on Rails developers.


Photo

How to fetch first and last records from a table?


  • Please log in to reply
2 replies to this topic

#1 Ajit Teli

Ajit Teli

    Passenger

  • Members
  • 1 posts

Posted 22 January 2014 - 06:37 AM

I would like to fetch first and last records for a time interval as below (it does not work).

 

Message.find([:first, :last], :conditions => ["created_at >= ? and created_at < ?", '2014-01-01', '2014-01-20'])

 

May I know how can I get it?

 

Thanks,

 Ajit



#2 Bharat Soni

Bharat Soni

    Dispatcher

  • Members
  • 54 posts
  • LocationAhmedabad

Posted 24 January 2014 - 05:09 AM

Hey you can not find records with two limits,

 

for find first and last record you have to make two queries like that...

 Message.find(:first, :conditions => ["created_at >= ? and created_at < ?", '2014-01-01', '2014-01-20'])

last record query 

 Message.find(:last, :conditions => ["created_at >= ? and created_at < ?", '2014-01-01', '2014-01-20'])

and if you do not wants to run two queries then you can fetch like that

messages = Message.find(:all, :conditions => ["created_at >= ? and created_at < ?", '2014-01-01', '2014-01-20'])

@first =  messages.first
@last = messages.last

Fun with Ruby on Rails


#3 Ohm

Ohm

    Guard

  • Members
  • 184 posts
  • LocationCopenhagen

Posted 24 January 2014 - 02:16 PM

 

Hey you can not find records with two limits,

 

for find first and last record you have to make two queries like that...

 Message.find(:first, :conditions => ["created_at >= ? and created_at < ?", '2014-01-01', '2014-01-20'])

last record query 

 Message.find(:last, :conditions => ["created_at >= ? and created_at < ?", '2014-01-01', '2014-01-20'])

and if you do not wants to run two queries then you can fetch like that

messages = Message.find(:all, :conditions => ["created_at >= ? and created_at < ?", '2014-01-01', '2014-01-20'])

@first =  messages.first
@last = messages.last

 

I believe that in order for first and last to work correct in this case, you'll need to order your relation by created_at as well.


Blog: http://ohm.sh | Twitter: madsohm





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users