0

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..

0

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

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

2 Comments

def self.find_showtimes(movie_id) find(:all, :conditions => ["movie_id = ?", movie_id], :order => 'time', :include => 'theater').group_by(&:theater) end This is the source for the finder function. The only way I can access these values is using an iterator. How can I access them directly?
@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.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.