In Ecto when should I use assoc_constraint vs foreign_key_constraint
Asked Answered
A

1

5

I know the difference between the two; assoc_constraint uses the ecto schema to validate the foreign key constraint, foreign_key_constraint uses the db.

Why would you ever use assoc_constraint in that case?

Atmometer answered 31/10, 2017 at 15:26 Comment(0)
B
16

If you look at the source of assoc_constraint and foreign_key_constraint, you'll see that they end with very similar call to add_constraint (private function)

assoc_constraint:

add_constraint(changeset, :foreign_key, to_string(constraint),
               :exact, assoc, {message, []})

foreign_key_constraint:

add_constraint(changeset, :foreign_key, to_string(constraint),
               :exact, field, {message, []})

The only difference between the two is, for foreign_key_constraint you give the exact name of the constraint, and for assoc_constraint, you give the name of the association and the function computes the foreign key name itself (using the same convention as Ecto migrations). Other than that, both work identically. assoc_constraint is just a convenience function so you don't have to use the exact name of the constraint, which is longer than the association name.

Bomb answered 31/10, 2017 at 15:33 Comment(1)
you are like the John Skeet of Elixir @BombAtmometer

© 2022 - 2024 — McMap. All rights reserved.