title: How to select particular fields from an association in Ecto?
body: <p>I have the following models</p>
  
  <pre class="lang-elixir prettyprint-override"><code>schema "products" do
    field :quantity, :integer
    field :price,    :float
    field :discount, :float, default: 0.0
  
    belongs_to :order, Order
  end
  
  schema "orders" do
    field :received_at,   Ecto.Date
    field :shipment_cost, :float
    field :savings,       :float
    field :shop_name,     :string
  
    has_many :products, Product
  end
  </code></pre>
  
  <p>What I want to do now is to fetch an order with a particular fields: <code>savings</code> and <code>shipment_cost</code>.</p>
  
  <p>I need also associated product for that order, but once again, also with only specific fields: <code>quantity</code>, <code>price</code> and <code>discount</code>.</p>
  
  <p>How to do that in the most efficient way?</p>
  
  <pre class="lang-elixir prettyprint-override"><code>def for_amount(order_id) do
    products_query = from product in Product,
                       select: %{
                         order_id: product.order_id,
                         quantity: product.quantity,
                         price:    product.price,
                         discount: product.discount
                       }
  
    from order in Order,
      preload: [products: ^products_query],
      where:   order.id == ^order_id,
      select:  [order.savings, order.shipment_cost]
  end
  </code></pre>
  
  <p>I also tried</p>
  
  <pre class="lang-elixir prettyprint-override"><code>def for_amount(order_id) do
    from order in Order,
      join:    products in assoc(order, :products),
      where:   order.id == ^order_id,
      select:  %{
                  savings:       order.savings,
                  shipment_cost: order.shipment_cost,
                  quantity:      products.quantity,
                  price:         products.price,
                  discount:      products.discount,
                }
  end
  </code></pre>
  
  <p>but this enforces me to use <code>Repo.all</code> and returns a list of joins of course.</p>