I have items (documents) in Ruby on Rails that have zero or many attributes. The document attribute has a type (“Author”, “Publisher” etc). Each document can have multiple attributes of the same type.
These are currently just pulled out the the db and listed as follows:
<% @document.attribute_documents.each do |doc_attr| %>
<b><%= doc_attr.attribute_type.try(:name) %>: </b>
<%= " #{doc_attr.value}" %>
<%= ", #{doc_attr.attribute_location}" unless doc_attr.attribute_location.blank? %>
<%= ", #{doc_attr.attribute_year}" unless doc_attr.attribute_year.blank? %><br />
<% end %>
Which gives a result like this, less than satifactory:
Publisher: William Cavell, Holborn, London
Printer: William Cavell, Holborn, London
Seller: J Barber, Newcastle
Seller: C Etherington, York
Seller: Fletcher and Hodson, Cambridge
Seller: Wilson, Dublin
What I am looking for is this:
Publisher: William Cavell, Holborn, London
Printer: William Cavell, Holborn, London
Sellers: J Barber, Newcastle, C Etherington, York, Fletcher and Hodson, Cambridge, Wilson, Dublin
So I need to group on attribute type, and then loop through the values depending on the type. Is there a simple way to doing this in RoR? Is my approach all wrong?
Use rails’
group_bymethod:Haven’t tested this, but I think it should work.
UPDATE: This will leave out commas between entries in each line. I’ll come back to it later, basically you need to use
mapand thenjoinon thedoc_attrsarray.UPDATE(2):
Here’s the expression that I was looking for, to go in the
doc_attrs.eachloop:I don’t use erb anymore so not quite sure how to translate it, but probably better anyway to create a helper function and build it up that way.