Ich habe zwei models, Person
und Pet
, und ich möchte ein Person
-have many Haustiere der Lage sein, aber ein Pet
-belong to nur eine Person:Elixir Ecto: Wie schreibe ich eine Migration mit gehört_zu und has_many?
defmodule MyApp.Person do
use MyApp.Web, :model
alias MyApp.Pet
schema "persons" do
field :name, :string
has_many :pets, Pet
timestamps()
end
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [])
|> validate_required([])
end
end
und
defmodule MyApp.Pet do
use MyApp.Web, :model
alias MyApp.Person
schema "pets" do
field :name, :string
belongs_to :person, Person
timestamps()
end
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [])
|> validate_required([])
end
end
So, wie schreibe ich eine migration dafür?
defmodule Iloveproblems.Repo.Migrations.CreatePersonsAndPets do
use Ecto.Migration
def change do
create table(:persons) do
add :name, :string
# I don't know :(. The has_many stuff
timestamps()
end
create table(:pets) do
add :name, :string
# I don't know :(. The belongs_to stuff
timestamps()
end
end
end
Ich benutze .
Vielen Dank im Voraus!
'add: person_id, Referenzen (: Personen), null: false' und so weiter als ein Weg zu gehen. – JustMichael