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

siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
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
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
dotdotdotPaul
Okay, I’m having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I’m sure I’...
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
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New

Other popular topics Top

New
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
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
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
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
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
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