Search code examples
elixirphoenix-frameworkecto

How to check undefined value when use preload and return no value with Ecto


I'm doing phoenix framework with ecto.

I wrote following code.

    query = from m in Member,
                 where: m.member_id == ^member_id,
                 preload: [:assoc1, :assoc2, :assoc3]

    Repo.all(query)

When all preloaded assocs has related values in DB, it works.

However when preloaded assocs do not have related value, it returns null. It cause error function nil.assoc3/0 is undefined in phoenix JSON view.

I would like to show JSON. I'm glad if I can get following JSON when assoc3 value is nil for example.

[{"member_id":1, "assoc1":"xxx", "assoc2":"yyy", "assoc3":""}]

Please give me advice how to manage no related nil values.


Solution

  • The issue does not seem to be with assoc3 being nil. According to the error message, the view attempts to call nil.assoc3 which means the database returned no result for the initial query (read: no Member.)

    You should validate the response from the database and render different pages for a successfully returned Member vs. nil.