Skip to content

Instantly share code, notes, and snippets.

@davejlong
Last active March 31, 2016 22:16
Show Gist options
  • Save davejlong/3037a1f3d751cbf44b839afcb5958f4e to your computer and use it in GitHub Desktop.
Save davejlong/3037a1f3d751cbf44b839afcb5958f4e to your computer and use it in GitHub Desktop.
Representing complex associations in Ecto
defmodule TaskRunner.Repo.Migrations.CreateLocations do
use Ecto.Migration
def change do
create table(:locations) do
add :type, :string
end
end
end
defmodule TaskRunner.Repo.Migrations.CreateTasks do
use Ecto.Migration
def change do
create table(:tasks) do
add :name, :string
add :source_id, references(:locations)
add :destination_id, references(:locations)
add :schedule, :string
end
end
end
defmodule TaskRunner.Models.Location do
use Ecto.Schema
import Ecto.Changeset
alias TaskRunner.Models.Task
schema "locations" do
field :type, :string
belongs_to :source, Task
belongs_to :destination, Task
end
@required_fields ~w(type)
@optional_fields ~w()
def changeset(location, params \\ :empty) do
location
|> cast(params, @required_fields, @optional_fields)
end
end
defmodule TaskRunner.Models.Task do
use Ecto.Schema
import Ecto.Changeset
alias TaskRunner.Models.Location
schema "tasks" do
field :name, :string
field :schedule, :string
# has_one :source, Location
# has_one :destination, Location
end
@required_fields ~w(name schedule)
@optional_fields ~w()
def changeset(task, params \\ :empty) do
task
|> cast(params, @required_fields, @optional_fields)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment