Iterate over Array of Objects and Return Attributes

14,003

Solution 1

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 }

Solution 2

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.

Solution 3

loe.article.map {|x| x.title} perhaps?

Solution 4

class LOE < ActiveRecord::Base
  has_many :articles
end

class Article < ActiveRecord::Base
  belongs_to :loe
end

loe.articles.select(:title).collect{|a| a.title}

map and collect are aliases, and you can call select(:fieldname) on an AREL to return just that field. You still get objects, but they're read-only and are populated with whatever the select returned, so to get the array of titles you need to do the collect.

Share:
14,003
BWStearns
Author by

BWStearns

Updated on July 27, 2022

Comments

  • BWStearns
    BWStearns almost 2 years

    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.

  • Andrey Deineko
    Andrey Deineko over 9 years
    the only answer to question