Tony
Tony

Reputation: 19181

How do you iterate over active record objects in Ruby On Rails?

This question is quite simple but I have run into the problem a few times.

Let's say you do something like:

cars = Vehicle.find_by_num_wheels(4)

cars.each do |c|
  puts "#{c.inspect}"
end

This works fine if cars is an array but fails if there is only one car in the database. Obviously I could do something like "if !cars.length.nil?" or check some other way if the cars object is an array before calling .each, but that is a bit annoying to do every time.

Is there something similar to .each that handles this check for you? Or is there an easy way to force the query result into an array regardless of the size?

Upvotes: 5

Views: 13948

Answers (4)

Subba Rao
Subba Rao

Reputation: 10696

Named scoped version for your problem

Vehicle.scoped(:conditions => { :num_wheels => 4 } ).each { |car| car.inspect }

Upvotes: 1

marcgg
marcgg

Reputation: 66535

You can do this to get arrays everytimes :

cars = Vehicle.find(:all, :conditions => {num_wheels => 4})

I don't think that you have a loop that will check if the object is an array.

Another solution could be:

for i in (1..cars.lenght)
  puts cars[i].inspect
end

(haven't tested, it might break to test the lenght on a string. Let me know if it does)

Upvotes: 1

Steve Madsen
Steve Madsen

Reputation: 13791

If you always want all of the cars, you should use find_all instead:

cars = Vehicle.find_all_by_num_wheels(4)

You could also turn a single Vehicle into an array with:

cars = [cars] unless cars.respond_to?(:each)

Upvotes: 2

erik
erik

Reputation: 6436

You might be looking for

cars = Vehicle.find_all_by_num_wheels(4)

The dynamic find_by_ methods only return one element and you have to use find_all_by_ to return multiple.

Upvotes: 12

Related Questions