Created
November 21, 2016 19:25
-
-
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
This file contains hidden or 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 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