group_by snippets

Grouping with group_by

Tagged group_by  Languages ruby
@groups = @products.group_by { |product| product.name.mb_chars[0].downcase.to_s }.sort

If you're using mb_chars, remember to call "to_s" or you won't get what you expect.

Ecto query using left join, group by, order by, and count

Tagged group_by, ecto, count, left_join, order_by  Languages elixir

This is an example of an Ecto query that uses a left join, group by, order by, and count to produce a count of associated records for a list:

query = from list in List,
  left_join: subscriber in assoc(list, :subscribers),
  group_by: list.id,
  order_by: [asc: :name],
  select: %{ list | subscriber_count: count(subscriber.id) }
query |> Repo.all

Remember to add a virtual attribute named subscriber_count:

schema "lists" do
  ...
  field :subscriber_count, :integer, virtual: true