I prefer the idea of pre-formatting the data into a hash (likely in the
model as a class method), then plopping the data into multiple collection
partials in the view, i.e.
#model
class Location < ActiveRecord::Base
def self.preformat_as_hash
self.each_with_object({}) do |location, acc|
acc[:addresses] ||=[]
acc[:addresses].push(location.address)
...
end
end
end
#controller
@formatted_locations = Location.where(somecondition).preformat_as_hash
#view
<table>
<tr>
<%= render partial: "locations/address", collection:
@formatted_locations[:addresses], as: :address %>
</th>
..
</table>
that way i keep any logic out of the views, i'm not looping over the
collection multiple times, my controller stays fairly clean etc.
On Monday, September 17, 2012 11:15:40 AM UTC-7, Chris McCann wrote:
>
> SD Ruby,
>
> I'm wrestling with a view that displays data from a collection of model
> objects in an HTML table with the data from each model instance shown in a
> column. I sense there's an elegant way to do what I'm trying to do but I'm
> at a loss as to how.
>
> The markup below shows how the end result should look. What I'm trying to
> avoid is having to look through the collection of instances to build each
> row.
>
> <div class="summary">
> <table>
> <tr>
> <th class="first"><a href="#">Summary</a></th>
> <!-- loop through collection and write this data for each instance -->
> <th><a href="#">201 First St.</a></th>
> <th><a href="#">1133 Columbia St.</a></th>
> </tr>
> <tr>
> <td class="first">Start Date</td>
>
> <!-- loop through collection and write this data for each instance -->
>
> <td>01/01/2010</td>
> <td>01/01/2010</td>
> </tr>
> <tr>
> <td class="first">Term</td>
>
> <!-- loop through collection and write this data for each instance -->
>
> <td>84 Months</td>
> <td>84 Months</td>
> </tr>
> </table>
> </div>
>
>
> Is there a better, more Railsy approach that I'm just not seeing? The
> actual table is much more complex than what's shown here so I don't want to
> go the CSS-only no table route unless there's a really nice solution that
> entails not using tables.
>
> Cheers,
>
> Chris
>
--
SD Ruby mailing list
[email protected]
http://groups.google.com/group/sdruby