Ruby/Rails - Add records to an object with each loop iteration / Object vs Arrays
Posted
by
ChrisWesAllen
on Stack Overflow
See other posts from Stack Overflow
or by ChrisWesAllen
Published on 2011-01-14T17:18:55Z
Indexed on
2011/01/14
18:53 UTC
Read the original article
Hit count: 232
I'm trying to figure out how to add records to an existing object for each iteration of a loop. I'm having a hard time discovering the difference between an object and an array.
I have this
@events = Event.find(1)
@loops = Choices.find(:all, :limit => 5) #so loop for 5 instances of choice model
for loop in @loops
@events = Event.find(:all,:conditions => ["event.id = ?", loop.event_id ])
end
I'm trying to add a new events to the existing @events object based on the id of whatever the loop variable is. But the ( = ) operator just creates a new instance of the @events object.
I tried ( += ) and ( << ) as operators but got the error
"You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil"
I tried created an array
events = []
events << Event.find(1)
@loops = Choices.find(:all, :limit => 5) #so loop for 5 instances of choice model
for loop in @loops
events << Event.find(:all,:conditions => ["event.id = ?", loop.event_id ])
end
But I dont know how to call that arrays attributes within the view
With objects I was able do create a loop within the view and call all the attributes of that object as well...
<table>
<% for event in @events %>
<tr>
<td><%= link_to event.title, event %></td>
<td><%= event.start_date %></td>
<td><%= event.price %></td>
</tr>
<% end %>
</table>
How could i do this with an array set?
So the questions are
1) Whats the difference between arrays and objects?
2) Is there a way to add into the existing object for each iteration?
3) If I use an array, is there a way to call the attributes for each array record within the view?
© Stack Overflow or respective owner