简体   繁体   中英

Ruby/Rails - Sorting and Presenting a Large Amount of associated data

I have a model that have a column for name and a column for categories. There are a large amount of names that I would like to list by category but I haven't figured out how to do it.

Currently in the view I have

<% for car in @cars %>
<%= car.name %>
<% end %>

which just presents this huge list of that is way too unwieldy. I'm using @car = Car.find(:all) in the controller to get the selection.

=> If there a way I can create some form of dynamic table where it groups all the car records by category and makes a new column for each category instance, with a listing of all the associated cars?

=> I'm also afraid that that might be too many columns so after 5 or so columns can I start a new row?

=> Should I do all this in the controller or the view?

Can you specify some sample values for the category column?

Depending on what you have stored you may be able to do this:

Car.find(:all).group_by(&:category)

Which will put the cars into an ordered hash indexed by the different category values.

<% @car_categories.sort.each do |category, cars| %>
    <h3><%= category %></h3>
    <% for cart in cars %>
       <p><%= interest.name %></p>
    <% end %>
<% end %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM