I have the below function which runs the query and returns the map
defp fetch_uid_data(%{admin_id: admin_id, uid: uid}) do
query = from(u in Uid,
where: u.admin_id == ^admin_id and u.uid == ^uid,
preload: [:products])
uid = Repo.one(query)
case uid do
nil ->
{:error, "Sorry! data not found"}
{:error} ->
{:error, "Data error"}
uid ->
{:ok, %{uid: uid.uid, scan_count: uid.scan_count,
admin_id: uid.admin_id, product_id: uid.product_id,
no_of_scans: uid.products.no_of_scans}}
end
end
Query Struct will be
%Uids.Uid{
__meta__: #Ecto.Schema.Metadata<:loaded, "uids">,
admin_id: "6a9700b4-509c-40bf-8780-b029da872c96",
id: 1,
inserted_at: ~N[2020-04-11 07:08:22],
product_id: "9a9700b4-509c-40bf-8780-b029da872c77",
products: %Protectivv.Products.Product{
__meta__: #Ecto.Schema.Metadata<:loaded, "products">,
admin_id: "6a9700b4-509c-40bf-8780-b029da872c96",
description: "Test TV",
id: "9a9700b4-509c-40bf-8780-b029da872c77",
images: #Ecto.Association.NotLoaded<association :images is not loaded>,
inserted_at: ~N[2020-04-11 07:08:22],
name: "TV",
no_of_scans: 5,
updated_at: ~N[2020-04-11 07:08:22],
videos: #Ecto.Association.NotLoaded<association :videos is not loaded>
},
scan_count: 0,
uid: "7a589",
updated_at: ~N[2020-04-11 07:08:22]
As you can see I am getting the no_of_scans field from a product’s association
uid.products.no_of_scans
Sometimes the product association will be null. That time this will throw an error.
So I want to know how to improve the above coding. In order to be robust.
I tried like this
query = from(u in Uid,
where: u.admin_id == ^admin_id and u.uid == ^uid,
preload: [:products],
select: %{uid: u.uid, scan_count: u.scan_count,
admin_id: u.admin_id, product_id: u.product_id,
no_of_scans: u.products.no_of_scans})
uid = Repo.one(query)
But it gives me the below error
** (Ecto.Query.CompileError)
u.products.no_of_scans is not a valid query expression. If you want to invoke u.products.no_of_scans/0 in a query, make sure that the module u.products is required and that no_of_scans/0 is a macro
If anyone can give me insight on how to improve my coding standard that will be greatly appreciated.Thanks.
Plus is there any course or ways to improve coding standards in elixir. Please share it. That will be a great help. Thanks