Reputation: 5314
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..
Upvotes: 0
Views: 4738
Reputation: 1127
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.
Upvotes: 0
Reputation: 18484
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
Upvotes: 2
Reputation: 21950
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.
Upvotes: 3