MatijaL

MatijaL

How should I handle attrs validations?

Hello,

I’m building a small app for learning purposes where I have users and those users can create projects. Projects can have different statuses and when the project status changes, embeded meta field is updated. Projects can also have multiple users so in the meta field I save who updated the project status.

# projects.ex
def update_project(%User{} = user, %Project{} = project, %{"status" => status} = attrs) do
    attrs = prepare_status_attrs(user, project, attrs)
    changeset = Ecto.Changeset.change(project)

    Repo.update(changeset)
end

defp prepare_status_attrs(%User{} = user, %Project{} = project, attrs) do
    cond do
        attrs["status"] == "draft" ->
            Map.put_new(attrs, "meta", %{"created_by" => user.id, "created_at" => NaiveDateTime.utc_now()})
            # other
        attrs["status"] == "active" ->
            Map.put_new(attrs, "meta", %{"activated_by" => user.id, "activated_at" => NaiveDateTime.utc_now()})
            # other
        attrs["status"] == "deleted" ->
            Map.put_new(attrs, "meta", %{"deleted_by" => user.id, "deleted_at" => NaiveDateTime.utc_now()})
            # other
    end
end

# meta_embed.ex
embedded_schema do
    field :created_at, :naive_datetime
    field :created_by, :string
    field :activated_at, :naive_datetime
    field :activated_by, :string
    field :deleted_at, :naive_datetime
    field :deleted_by, :string
    # other fields
  end

def changeset(%MetaEmbed{} = meta, attrs) do
    meta
    |> cast(attrs, [:created_at, :created_by, :activated_at, :activated_by, :deleted_at, :deleted_by])
  end

The code above is a little bit simplified but what I have is a function that prepares the attrs in my projects.ex file before it goes to changeset and there are no changeset validations. The reason why I’m doing it is simply because here I have access to the user data etc. Is this a good practice or should I change the logic, pass all the user data to changeset and then do all the validations with changeset?

Where Next?

Popular in Questions 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
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
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
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29377 241
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43622 214
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
klo
Got a question about when to concat vs. prepending items to list then reversing to achieve appending. So i know lists boil down to [1 | ...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
marick
I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I’m a nov...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement