I have a User
model defined with:
belongs_to :institute, Mango.Institutes.Institute
field :prefix, :string, virtual: true
And an Institute
model defined with:
field :prefix, :string
When using the application I need to have the prefix
filed value for the institute
the user
belongs to.
What I have done so far to do that is this, inside Accounts
context (the User
context):
# mofified to load user institute's prefix
def get(id) do
Repo.get(User, id)
|> case do u -> Map.put(u, :prefix, get_institutes_prefix(u.institute_id)) end
end
def get_institutes_prefix(id) do
Repo.get(Mango.Institutes.Institute, id).prefix
end
Works fine, but this means that the database is called twice, once to get the user and once to get institutes prefix value.
My question, how to optimize all of this? Is it possible to generate once in a while (in code) (or upon creating new institutes) some .ex
file with all those institute_id
- prefix
key value pairs and retrieve the prefix value for users in code without querying the database?
Thank you.