sglyon
I am an experienced dev, but pretty new to elixir. I keep finding myself going back and forth between a couple options for how to construct a changeset that will create a new record with one or more associations.
The following small ecto schema module presents the two options
defmodule MyProject.Quizzes.QuizQuestion do
use Ecto.Schema
import Ecto.Changeset
schema "quiz_questions" do
belongs_to :quiz, MyProject.Quizzes.Quiz
belongs_to :question, MyProject.Questions.Question
timestamps()
end
@doc false
def changeset(quiz_question, attrs) do
quiz_question
|> cast(attrs, [:quiz_id, :question_id])
|> validate_required([:quiz_id, :question_id])
|> foreign_key_constraint(:quiz_id)
|> foreign_key_constraint(:question_id)
end
def create(%MyProject.Quizzes.Quiz{} = quiz, %MyProject.Questions.Question{} = question) do
%__MODULE__{}
|> change()
|> put_assoc(:quiz, quiz)
|> put_assoc(:question, question)
|> foreign_key_constraint(:quiz_id)
|> foreign_key_constraint(:question_id)
end
end
In this example I have three models: Quiz, Question, and a join table QuizQuestions that combines them. I have two functions in the module:
change: this takes in anattrsmap, casts the foreign keyid, requires them, and adds foreign key constraintscreate: takes in instances of the related schemas (Question and Quiz), usesput_assocto build the association, then adds foreign key constraints
Both of these approaches let me create the new QuizQuestion struct that is Repo.insertable, but I still have some questions.
- Is one approach more idiomatic and why?
- Should I prefer one case to the other?
- What are the tradeoffs?
- Is it bad practice to use structs defined in other core modules as arguments to functions (like I did in
createwhen I acceptQuizandQuestionstructs)?
Trending in Questions
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
Hello,
I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind.
However, when I launch mix phx.server, I get an error...
New
Hi everyone.
My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
Hello folks!
So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
I’m working on a small exercise involving update_in/3, and I came up with this solution:
data = %{
name: "Periodic Table",
category:...
New
How Can I Optimise Compile Time Dependencies
I have been building an elixir application for about 2 years now. Many modules and files ha...
New
Other Trending Topics
Edit: 2026 May 15 - This post is archived.
Mob is alive!!
Main docs: mob v0.7.11 — Documentation
A bit of explanation for the slightly c...
New
A little off-topic, but I feel like people here have a good head on their shoulders.
I used to be quite good at making software. Was luc...
New
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #ai
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixirconf-us
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #elixirconf-eu
- #api
- #forms
- #security
- #metaprogramming










Showing Posts 1 to 4- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
al2o3cr
I’m going to give you the less-than-entirely-helpful “it depends”
Both approaches can be useful, depending on exactly where
quizandquestionare coming from:casts them could be useful to make sure they’re converted to the ID type etcput_assocapproach is fine/quiz/1234/questionswhere theQuizto associate is known but thequestion_idto use is from the userIn the “neither from the user” case, you might even shorten things further if you don’t want / need to display foreign key errors as changeset errors:
This can be passed to
Repo.insertdirectly, no changeset required.Two general things to think about:
For instance on the second point, a field that a user could leave blank might have
validate_requiredon it so they could be told they’re making a mistake. OTOH a field that the program fills in that shouldn’t ever be blank might just have a bareNOT NULLin the DB so failing to fill it in crashes / fails.lucavenir
I hope I don’t startle anyone asking this 2 years later.
But in reality
1234comes as a binary, doesn’t it?So, related to this, given that we need to cast
"1234"to1234, how would one code the changeset function, here?garrison
The implication here is that if you are on
/quiz/1234then you have already done aRepo.get(Quiz, id)and you have a%Quiz{id: 1234}to work with.Personally, in that situation I often do something like this:
But it would be just as valid to work with associations or use
put_change()for thequiz_id. The point is that you don’t need to castquiz_idbecause it comes right from a real%Quiz{}and it’s already an integer.lucavenir
This means that if I have:
/resource/:resource_id/child/:child_id/feature/:idI need to perform at least two
gets, internally, to determineresourceandchild- did I get this right?I may go off topic, but isn’t this suboptimal?
Is it a premature optimization concern?
Thank you for the great answer btw.