sglyon

sglyon

Best practice for association changesets

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 an attrs map, casts the foreign key id, requires them, and adds foreign key constraints
  • create: takes in instances of the related schemas (Question and Quiz), uses put_assoc to 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 create when I accept Quiz and Question structs)?

Most Liked

al2o3cr

al2o3cr

I’m going to give you the less-than-entirely-helpful “it depends” :stuck_out_tongue:

Both approaches can be useful, depending on exactly where quiz and question are coming from:

  • if both are coming from the user, an approach that casts them could be useful to make sure they’re converted to the ID type etc
  • if neither are coming from the user, the full put_assoc approach is fine
  • it’s also possible to have a mix - maybe the function is being called from a URL like /quiz/1234/questions where the Quiz to associate is known but the question_id to use is from the user

In 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:

def just_create_already(quiz, question) do
  %__MODULE__{quiz: quiz, question: question}
end

This can be passed to Repo.insert directly, no changeset required.

Two general things to think about:

  • where is the input coming from? Does it need to be type-cast?
  • where should errors appear? Are they meaningful?

For instance on the second point, a field that a user could leave blank might have validate_required on 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 bare NOT NULL in the DB so failing to fill it in crashes / fails.

garrison

garrison

The implication here is that if you are on /quiz/1234 then you have already done a Repo.get(Quiz, id) and you have a %Quiz{id: 1234} to work with.

Personally, in that situation I often do something like this:

def create_question(%Quiz{} = quiz, params) do
  %Question{quiz_id: quiz.id}
  |> Question.changeset(params)
  |> Repo.insert()
end

But it would be just as valid to work with associations or use put_change() for the quiz_id. The point is that you don’t need to cast quiz_id because it comes right from a real %Quiz{} and it’s already an integer.

Where Next?

Popular in Questions Top

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
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
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
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
Kagamiiiii
Student & New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New

Other popular topics Top

peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
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
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New

We're in Beta

About us Mission Statement