views:

241

answers:

3

Easy question: I need help writing an ActiveRecord find_all_by statement where I want to order things from newest created objects to oldest.

As a follow-up to this question: If I saved the results into a variable @records. How do I then ask for the next record in it? I want to do something like @current_record = @records.next

+5  A: 

This code will do your initial query

 @records = Model.find_all_by_column('value', :order => 'created_at DESC')

And with regards to your follow up. If you want to iterate over the returned array then you can do the following

 @records.each do |record|
  # Code to do something
 end

Within the iterator you could set a flag when you see a particular record then do something with the next record in the iterator.

If you wish to check whether there are any records in the array returned by the finder then you can check @records.length

Steve Weet
is each. do the only control structure in Ruby when you have a set of records?
alamodey
Also, how do you check if @records actually has any objects? I did a if @records == nil check but it seems that is false even when I have nothing in the Model table.
alamodey
There are all kinds of ways to iterate across arrays, which is what you have with an ActiveRecord result. Try looking at http://apidock.com/ruby/Array , http://apidock.com/ruby/Enumerable (Array mixes this in) and there are more added by ActiveSupport in Rails.
Mike Woodhouse
Oh, and @records, if empty, will be an empty array, so you could test for @records == [] or @records.size == 0
Mike Woodhouse
use @records.empty? to check for an empty @records variable
vrish88
A: 
Model.find_all_by_column_name('something', :order => "...")
August Lilleaas
A: 

for question 2: what do you mean by "the next record in it" ?

if you search for a way to display results, it's convenient to use each:

<% @records.each do |record| %>
   #...
<% end %>

Or even better, with a partial

<%= render :partial => 'record', :collection => @records %>
Gaetan Dubar