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

This question is quite simple, but I have come across a problem several 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 are an array, but fail if there is only one car in the database. Obviously, I could do something like "if! Cars.length.nil?" or check another way if the car object is an array before calling .each, but it's a bit annoying to do it every time.

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

+5
source share
4

,

cars = Vehicle.find_all_by_num_wheels(4)

find_by_ , find_all_by_ .

+12

, find_all :

cars = Vehicle.find_all_by_num_wheels(4)

Vehicle :

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

Named version for your problem

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

You can do this to get arrays every time:

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

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

Another solution might be:

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

(not tested, it may break to check the length of the string. Let me know if that is)

0
source

All Articles