У меня есть два models, Person
и Pet
, и я хочу Person
, чтобы иметь возможность have many домашних животных, но Pet
к belong to только один человек:Elixir Ecto: Как написать переход с собственными_и и 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
и
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
Итак, как я пишу для этого migration?
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
Я пользуюсь .
Заранее благодарен!
'add: person_id, ссылки (: люди), null: false' и т. Д. Как один из способов. – JustMichael