0

I don't even know how to ask this correctly, so pardon me if my question is confusing. I have a Table called Colors -

Sample Colors Table

I would like to iterate a list of all the colors in the table, but presorted by 'color-family' so the result would look something like this:

Colors:
   Reds -
      Maroon
      Stop Sign
   Yellows -
      Canary
   Blues - 
      Sky Blue
      Royal Blue
   Greens -
      Neon Green

But I have no idea the sql syntax to collect and sort that kind of information.
Surprisingly, this code didn't work ;)

<% @group = Colors.presort_by("color-family") %> 
<% @color = Colors.all %>
<% @group.each do |group| %>
  <%= group.color-family %>s - <br>
  <% if @[email protected] %>
  <%= @color.name %>
  <% end %>
 <% end %>

lol. As you can see, I have no real idea where to start. Any help would be greatly appreciated. I don't have any sql query experience whatsoever.

Thanks again!

1
  • @colors = Color.order(:color-family ,:name) something like this, depends what order you want. You could reference here Commented Dec 30, 2016 at 5:42

1 Answer 1

1

I'm not sure if there's a way to do this using just ActiveRecord query methods. But it can easily be done in-memory using Ruby's Enumerable#group_by, and the performance will be good unless it's a large data set (in which case you'd probably want to cache the results, or look into a more complex SQL query)

@colors = Color.all
grouped = @colors.group_by { |color| color.color_family }
# or             .group_by &:color_family

This will return a hash where keys are color family (strings) and values are arrays of Color records.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.