Search code examples
elixirphoenix-frameworkecto

Adding a virtual field to an object


  def list_links_count do

    query = 
      from l in Link,
        join: c in Click, as: :click,
        where: c.link_id == l.id,
        group_by: l.id,
        select: {l, count(l.id)}

    query |> Repo.all

  end

I've got a function that counts that number of clicks per link. The problem is with the final data structure, which is of the form {Link, 10}. What I'd really like to do is have it put_in the total, so I can access it more easily in a view, something like link.click_count. Is that possible?


Solution

  • Do you have the virtual field on your Ecto schema for Link? If not, you'll want to add it:

    field(:click_count, :integer, virtual: true)
    

    Then your select could look something like this:

    select: %{l | click_count: count(l.id)}
    

    Since you now have a click_count key in your Link structs, you can put that key and still have a list of Links. So you should be able to access link.click_count.