Last active
September 22, 2016 19:48
-
-
Save Ivor/6c59b45e2aa982b13e27e06fc486b3f2 to your computer and use it in GitHub Desktop.
Ecto: How to validate unique combinations of two fields.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule VetMapper.Branch do | |
use VetMapper.Web, :model | |
schema "branches" do | |
field :name, :string | |
field :country, :string | |
field :state, :string | |
field :city, :string | |
field :street_name, :string | |
field :street_number, :integer | |
belongs_to :clinic, VetMapper.Clinic | |
end | |
def changeset(struct, params \\ %{}) do | |
struct | |
# Note that the constaint is placed on ONE of the fields. | |
|> unique_constraint(:street_number, name: :index_branches_on_address) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule VetMapper.Clinic do | |
use VetMapper.Web, :model | |
schema "clinics" do | |
field :name, :string | |
has_many :branches, VetMapper.Branch | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Migration can be found here: https://gist.github.com/Ivor/815f9128fc73b162118dd6cdcc0b48e9
Blog post: https://medium.com/@ivorpaul/ecto-how-to-validate-unique-combinations-of-multiple-fields-8002c74c6757#.f1iwh3dzf