I am trying to return a list of titles of objects in Rails, however I keep getting the entire object returned instead of the title attribute.
loe is the object which has an attribute which is a list of articles (named article), each article is itself an object with an attribute called title.
<%= loe.article.each { |x| print x.title } %>
is how I am currently attempting to do the iteration, but this returns the entire list of articles.
Use Array#forEach method for array iteration.
Method 1: Using for…in loop: The properties of the object can be iterated over using a for..in loop. This loop is used to iterate over all non-Symbol iterable properties of an object.
You have to pass the object you want to iterate, and the JavaScript Object. keys() method will return an array comprising all keys or property names. Then, you can iterate through that array and fetch the value of each property utilizing an array looping method such as the JavaScript forEach() loop.
A for loop can be used to access every element of an array. The array begins at zero, and the array property length is used to set the loop end.
Use Array#map
to invoke the title
method on each and create a new array with the results:
loe.article.map(&:title)
The above is shorthand for
loe.article.map{ |o| o.title }
Using the ERB tag like '<%=
' means that you're asking ERB to display the result of that expression (above and beyond the fact that you're calling print
inside the block). And a call to an Enumerable method like each
will return the original array, which is what you're seeing.
Change the tag to <%
(remove the =
) and you should be good to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With