jgb-solutions
What's the easiest way to populate ecto's virtual field with database data
Hey guys! I have an Album module with an Ecto schema. The schema has a cover_url virtual field that depends on the cover column to return the url for the cover.
I have this code that uses a function on the module to build the url. Now the issue is that album is not passed to the function. It raises an error instead stating: variable "album" does not exist and is being expanded to "album()", please use parentheses to remove the ambiguity or change the variable name
The function that builds the url looks like this:
This stuff is so easy to do in other framework such as Laravel. I’m building my first big app in Elixir/Phoenix in part to learn the platform. I realize that this platform makes most hard things in other languages/tools easy and some easy things hard. Thanks for you help!
Most Liked
shanesveller
An additional option for some cases is Ecto.Query.select_merge which can populate virtual fields on your schema directly at read-time if the desired content can be calculated via SQL with fragment. This is something that you should measure the performance impact of but is generally within tolerances for queries that don’t produce an enormous number of rows.
christhekeele
This was very helpful to me @shanesveller, select_merge with a fragment is exactly what I wanted!
Took a little fumbling around to figure out exactly what to do, since none of the docs nor linked docs describe using fragments this way, so for reference:
defmodule Answer do
use Ecto.Schema
schema "answer" do
field :word, :string
field :length, :integer, virtual: true
end
end
Repo.insert(%Answer{word: "SWANS"})
Repo.one(
from answer in Answer,
select_merge: %{length: fragment("length(word)")}
)
#=> %Answer{word: "SWANS", length: 5}
benwilson512
Tangentially, when posting code, please always use text instead of images. Text allows those who are helping to easily make suggested edits without retyping everything, and it’s also more accessible across a variety of screen sizes and resolutions.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance











