I’m trying to define a new array through a where query but I can only get it to work one way.
Here it is:
<%
@children = Array.new
Topic.where(breadcrumb_id: @topic.id).each do |y|
@children.push(y.name)
end
return @children
%>
Returns the array ["Performance Arts", "Visual Arts", "Physical Arts", "Music", "Culinary Arts"] (All topics)
But I would prefer just to do
@children = Topic.where(breadcrumb_id: @topic.id)
return @children.each.name
Returns "undefined method `name' for #<Enumerator:0x007fe92205a1f0>"
For whatever reason .each won’t respond correctly… although it works on the initial where call in the first example. What’s the difference?
and Is there a way to do this so that I can pull the names directly through the array?
The #where method returns an ActiveRecord::Relation object, not an array.
To get an array, call #all or #to_a on it:
Note that you don’t need to convert it to an array in order to iterate over it.
Check out Frederick Cheung’s answer to why your use of #each doesn’t work.