group_by snippets

Grouping with group_by

Tagged group_by  Languages ruby
@groups = @products.group_by { |product|[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),
  order_by: [asc: :name],
  select_merge: %{ subscriber_count: count( }
query |> Repo.all

Remember to add a virtual attribute named subscriber_count:

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

Tested with Ecto 2.2.