From my controller I am passing two instance variables @events = Event.all and @images = Images.all. In the view I begin by iterating through @events.each do |event| and within this block is the line img = @images.shift yet when I try to access any method of img such as img.filename I get an error that img is nil but I have checked and am certain that @images is populated correctly. If I simply output img.class I receive the correct class, Image, but cannot access any of it’s methods.
What am I doing wrong or why is this way of pulling instances from an array incorrect?
I know there are other ways of going about this but this specific problem confounds me and I would really like to understand why this doesn’t work. Thanks.
#Structure of the model is
Image
-filename :string
-date :datetime
-caption :text
-source :string
#Controller
def index
@events = Event.all
@images = Image.all
end
#index.html.erb
<% @events.each do |event| %>
... code that works ...
<% if count==1%>
<% img = @images.shift %>
<div><%= img.filename %></div>
<% end %>
<% end %>
#For testing purposes I changed
<% img = @images.shift %>
<div><%= img.class %></div>
#output is Image
The problem might occur when there is more events then images. Because every time an iteration goes through @events array then the @images are shifted and is taken the next element from the array. So when you have for example 4 elements in @events and only 3 in @images then at 4th iteration there is taken 4th element from @images and this is
nil