2017-02-09 5 views
2

私は2 modelsPersonPetを持っている、と私はPersonhave manyペットにできるようにしたいが、Petbelong toにたった一人:どのように、エリクサーエクト:belongs_toと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 

私はを使用しています。

ありがとうございます!

+2

'add:person_id、references(:persons)、null:false'などのように移動します。 – JustMichael

答えて

2

私はここで私のコメントを移動すると思います。

外部キーとして使用されているフィールドを作成するためには、あなたがこのような何か書くことができます。

add :person_id, references(:persons), null: false 

をこのフィールドが(必ずしも必要ではない)nullでなく、それはdoesnのことをすることを保証します参照整合性を破棄する。

関連する問題