views:

1875

answers:

3

Hello

My issue involves an array that is apparently not nil but when I try to access it, it is.

The array is returned from a find on an active record. I have confirmed it is in fact an array with the .class method

@show_times = Showing.find_showtimes(params[:id])
@show_times.inspect =>shows that the array is not empty and is a multidimensional array.
@show_times[0] =>is nil
@show_times[1] =>is nil
@show_times.first.inspect => NoMethodError (undefined method `first')

I am perplexed as to why this is..

+2  A: 

find_showtimes is not a built-in finder - if it were, it would return either a single ActiveRecord object or an array of ActiveRecord objects - never a multidimensional array. So the first thing I'd do is have a look a the source of that method.

EDIT: Given your source code (in the comment) - you're actually getting a Hash, not an Array, back from your finder. See the docs for Enumerable's group_by. The Hash is mapping your theater objects to an array of showing objects. This is what you want to do:

Showing.find_showtimes(params[:id]).each do |theater, showtimes|
  puts "Theater #{theater} is showing the movie at #{showtimes.join(', ')}"
end
Sarah Mei
rube_noob
@rube_noob See my answer below. What you are getting is _not_ an Array. You can generally convert it to one with to_a, or you could add the array like functions it's missing by hand (e.g. def x.first; self[0]; end) but it isn't really an Array.
MarkusQ
+3  A: 

It's not an array, it's an active record magic structure that mostly looks like an array. I think you can do to_a on it to get a real array, but then a lot of the magic goes away.

MarkusQ
Actually, if you look at his code for the finder (it's in the comment in my answer), he's getting a Hash back.
Sarah Mei
A: 

If you're in the console and you want to explore the @show_times object, you can use the keys method to see all the hash keys and then get to individual hash items (such as all the show times) like so:

@show_times[:theater_one]

Same thing will work in your model/view but using each/map/collect would be cleaner as pretty code goes.

inkdeep