quazar

quazar

How to encode ecto schema with Jason with all fields

How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes. Just want it simple without much config.

@derive {Jason.Encoder, except: [:__meta__, :__struct__]} 

I tried this but it failed when association was not loaded. Is there a way I can specify to encode all attributes of schema and association which are preloaded and drop associations which are not loaded.

Most Liked

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

You’ve tagged this with Phoenix which makes me think you’re doing this in order to render a schema for an API. The suggested approach is to not do this with encoder protocols but rather with JSON views: JSON Views in Phoenix | RokkinCat

scooter

scooter

If anyone stumbles across this, the blog post referenced regarding why to use JSON views versus encoder protocols has changed URLs: https://rokkincat.com/blog/2015-03-17-json-views-in-phoenix/

amnu3387

amnu3387

You can define the Jason.Encoder protocol for the structure you want, so that it automatically does that, although I’m not positive this should be done instead of explicitly loading or discarding the fields according to where in the code you’re accessing the records, since this will discard that information always, e.g:

defimpl Jason.Encoder, for: [Your.Module] do
  def encode(struct, opts) do
    Enum.reduce(Map.from_struct(struct), %{}, fn
      ({k, %Ecto.Association.NotLoaded{}}, acc) -> acc
      ({k, v}, acc) -> Map.put(acc, k, v)
    end)
    |> Jason.Encode.map(opts)
  end
end

Notice now that this becomes implicit behaviour whenever Jason’s encode is called on this structure.

Other ways of doing it is to have a function that you call at the end of your load, or explicitly querying with a select, substituting the values explicitly when you don’t need them (this makes it so, that it’s explicit on the code actually running where that step is happening, instead of a catch all) e.g:

YourSchema |> where([ys], ys.id == 1) |> select([ys], %YourSchema{ys | associaton_field: nil}) |> Repo.one

Where Next?

Popular in Questions Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
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
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 53690 245
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
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 126479 1222
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

We're in Beta

About us Mission Statement