tomr
tomr

Reputation: 1134

Add to each enumerable a calculated value

I am trying to fetch "work_items" from the database, calculate a value, add it to the respective work_item and then continue, but I can't figure out why it does not work:

import Ecto.query, warn: false

  def list_work_items do
    WorkItem
    |> select_merge([work_item], %{value: ^work_item_value(work_item)})
    |> Repo.all()
  end

  defp work_item_value(work_item) do
    work_item.duration_in_minutes/60 * work_item.hourly_rate_in_cents
  end

When I run mix phx.server I get:

warning: variable "work_item" does not exist and is being expanded to "work_item()", please use parentheses to remove the ambiguity or change the variable name
  lib/fourty/tracking.ex:22: Fourty.Tracking.list_work_items/0


== Compilation error in file lib/fourty/tracking.ex ==
** (CompileError) lib/fourty/tracking.ex:22: undefined function work_item/0
...

22 is the one with the select_merge.

I have googelt and tried the docs, but can't figure out why it does not work. Help would be appreciated.

Upvotes: 0

Views: 78

Answers (1)

tomr
tomr

Reputation: 1134

I figured it out - the solution is to use a virtual field:

field :value, :float, virtual: true

and then use:

  def list_work_items do
    WorkItem
    |> select_merge([work_item], %{value: fragment("?/60 * ?"), work_item.duration_in_minutes, work_item.hourly_rate_in_cents})
    |> Repo.all()
  end

Upvotes: 3

Related Questions