Skip to content

Instantly share code, notes, and snippets.

@abitdodgy
Created November 21, 2016 19:25
Show Gist options
  • Save abitdodgy/04549c7372ba62f4614b3fd4c0565116 to your computer and use it in GitHub Desktop.
Save abitdodgy/04549c7372ba62f4614b3fd4c0565116 to your computer and use it in GitHub Desktop.
Medium Article: Building Many-to-Many Associations with cast_assoc and Nested Forms in Phoenix and Ecto
defmodule App.Account do
schema "accounts" do
field :name, :string
has_many :memberships, App.Membership
has_many :users, through: [:memberships, :user]
end
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:name])
|> validate_required([:name])
end
end
defmodule App.User do
schema "users" do
field :email, :string
has_many :memberships, App.Membership
has_many :accounts, through: [:memberships, :account]
end
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:email])
|> validate_required([:email])
|> unique_constraint(:email)
end
end
defmodule App.Membership do
schema "memberships" do
belongs_to :account, App.Account
belongs_to :user, App.User
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment