fireproofsocks
Defining read-only fields in Ecto Schema
I have an Ecto Schema which needs to restrict certain fields from being updated (for business reasons). What is the best way to do that? I saw this old issue in git: Way to specify field as read-only (do not insert)? · Issue #629 · elixir-ecto/ecto · GitHub but I couldn’t get before_insert or before_update to work anywhere (a full example would have helped). Is this even possible with the current version of Ecto? How are others accomplishing this?
thanks!
Marked As Solved
Ankhers
This is a perfect scenario for two changeset functions!
def changeset(struct, params) do
struct
|> cast(params, list_of_all_fields())
|> validation_one()
|> validation_two()
end
def update_changeset(struct, params) do
struct
|> cast(params, list_of_updateable_fields())
|> validation_three()
|> validation_four()
end
Never feel like you have to pack everything into a single changeset function. You can always create as many as you need for a given module.
Also Liked
NobbZ
The before_* hooks have been removed in the very early days.
But perhaps you can build something around validate_change/3?
validate_change(cs, :read_only_field, fun :read_only_field, _ -> [read_only_field: "not allowed to change"] end)
NobbZ
No, it will invalidate the Changesset and append to the error list.
Don’t do this. Tell the user that (s)he is wrong, do not simply alter his/her provided data, (s)he will complain. But it should be possible as well, but you’ll need to do some extra work, as ecto isn’t build for that.
kwando
Just remove the “read only” fields from your Ecto.Changeset.cast or Ecto.Changeset.change function.
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








