fireproofsocks

fireproofsocks

Adding calculated fields to Ecto Schema - virtual field or?

I’m wondering the best way to solve this particular problem: I have a schema for file uploads (think of an asset manager). The database record stores the file size, the file name, and its location. I also have a Phoenix endpoint where one can stream that file, e.g. for use as a src in an <img> tag. The route is something like /download/:id.

My question is: how to add a field to the Ecto Schema where I can populate the download url? The schema struct already knows the ID of a record, so the only thing I need to do is to build the URL using one of the Phoenix route helpers. Would this require a custom type?

Marked As Solved

lindem

lindem

I usually have a function in my schema’s defmodule that fills virtual fields for that purpose (full name field example), which is called from functions in the context after the actual Repo interaction.

As far as I know, there is no way to have something that looks like you do map.prop but that does getter_for_prop(map) instead (like, for instance, ember computed properties or more generally ES6 getters and setters).

It looks like this (off the top of my head):

def get_person(id) do
  case Repo.get(Person, id) do
     {:ok, person} -> {:ok, Person.fill_virtual_fields(person)}
     other -> other
  end
end

(You can pipe a list of schema instances through Enum.map())

Also Liked

amnu3387

amnu3387

I think virtual fields are a good use case for it,
For instance:

defimpl Jason.Encoder, for: WhateverSchema do
  def encode(struct, opts) do
    struct
    |> Map.put(:avatar, RunTimeSettings.get_url_for(struct))
    # |> maybe_trim_private_fields()
    |> Jason.Encode.map(opts)
  end
end

Personally, if the full url is the only thing that makes sense for the client(s), I replace the field itself with the valid url, if the client needs/can use the field value for something, I define a virtual field and then populate that instead.

al2o3cr

al2o3cr

Do you need the data on the schema itself, or is it sufficient to include the URL when the struct is serialized to JSON? In the latter case, @amnu3387’s solution will do exactly what you need.

In the former case, things are more complicated - invoking route helpers from inside schemas will mean a circular dependency between the data layer and the Phoenix layer.

fireproofsocks

fireproofsocks

That makes sense – is :avatar a virtual field in that example? I haven’t tested that, but is the virtual field even necessary if you are just putting a field into a map?

And I guess for thoroughness, I would love to see an example of how to add something to the schema. E.g. the class accessor example of having a first_name and last_name field in the database, and then having a “virtual” field for full_name that concatenates the two together.

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New

We're in Beta

About us Mission Statement