Last active
March 31, 2016 22:16
-
-
Save davejlong/3037a1f3d751cbf44b839afcb5958f4e to your computer and use it in GitHub Desktop.
Representing complex associations in 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 TaskRunner.Repo.Migrations.CreateLocations do | |
use Ecto.Migration | |
def change do | |
create table(:locations) do | |
add :type, :string | |
end | |
end | |
end |
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 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 |
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 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 |
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 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