yos1p

yos1p

Computing Ecto virtual field

Suppose I have this following schema:

schema "items" do
    field :code, :string
    field :name, :string
    field :sell_price, :decimal

    timestamps()
end

I wanted to have a virtual field, where it will format my sell_price field as string. I recall, in Ecto, you can do this:

field :formatted_sell_price, :string, virtual: true

My question is, how to make Ecto always compute that field to the format that I want? Suppose I already have my own formatting code with Money or Number.

Most Liked

kip

kip

ex_cldr Core Team

TLDR; no, not really. And overall, the explicit functional approach is preferred.

I recommend reading this thread for some good discussion on this topic: Hook function in Ecto.Schema to set virtual fields when querying a Schema struct from the data store - #8 by johmue

Aetherus

Aetherus

  1. When you need a computed field, you actually need a function.
  2. Functions are not data, so they should not reside in structs.
  3. If you only want that formatted_sell_price in JSON serialization, you can define your own impl of Jason.Encoder for your Item structs:
defimpl Jason.Encoder, for: Item do
  def encode(%Item{sell_price: price} = item, opts) do
    item
    |> Map.from_struct()
    |> Map.delete(:__meta__)
    |> Map.put(:formatted_sell_price, format_price(price))
    |> Jason.Encode.map(opts)
  end
end

You need to replace Item with your schema module, and format_price with your own function of formatting prices.

yos1p

yos1p

I would like to use it in my .eex file. What’s the best way to do this? So that I can simply use something like <%= item.format_price %> and that’s it.

If I use a function there, I find that I have to call something like:

<%= ElixirApp.MasterData.Item.format_price(item) %>

Is there any way to avoid that?

Where Next?

Popular in Questions Top

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
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
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New

Other popular topics Top

hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43806 214
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36432 110
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
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

We're in Beta

About us Mission Statement