2017-10-03 5 views
1

私は一対多の関係を確立しようとしています。ユーザーは任意の数の投稿を作成できます。フェニックス1.3、エクト2.2.1Ecto(Phoenix 1.3)に関係を追加する

#migrations 
defmodule MyApp.Repo.Migrations.CreateUsersPosts do 
    use Ecto.Migration 

    def change do 
    create table(:users) do 
     add :email, :string, null: false 
     add :handle, :string, null: false 
     add :password_hash, :string, null: false 

     timestamps 
    end 
    end 
... 
    def change do 
    create table(:posts) do 
     add :title, :string 
     add :users_id, references(:users, on_delete: :delete_all) 
     add :content, :text 

     timestamps() 
    end 
    create index(:posts, [:users_id]) 

    end 
end 

#models 
defmodule MyApp.User do 
    use MyApp.Web, :model 

    @derive {Poison.Encoder, only: [:id, :email, :handle]} 

    schema "users" do 
    field :email, :string 
    field :handle, :string 
    field :password_hash, :string 

    has_many :posts, MyApp.Post 
    timestamps 
    end 
end 

defmodule MyApp.Post do 
    use Ecto.Schema 

    schema "posts" do 
    field :title, :string 
    field :content, :string 
    belongs_to :users, MyApp.User 

    timestamps() 
    end 
end 

#seeds.exs 
MyApp.User.changeset(%MyApp.User{}, %{ 
    email: "[email protected]", 
    handle: "me", 
    password_hash: Comeonin.Bcrypt.hashpwsalt("me")}) 
|> MyApp.Repo.insert! 

user = MyApp.Repo.get_by(MyApp.User, email: "[email protected]") 
MyApp.Post.changeset(%MyApp.Post{}, %{ 
    title: "title", 
    content: "content", 
    users_id: user.id 
}) 
|> MyApp.Repo.insert! 

私が移行し、シードを実行すると、私はポストを照会するとき、私は以下を参照してください。

%MyApp.Post{__meta__: #Ecto.Schema.Metadata<:loaded, "resources">, 
    content: "content", title: "title", 
    users: #Ecto.Association.NotLoaded<association :users is not loaded>, 
    users_id: nil} 

ユーザーIDを正常に取得できたにもかかわらず、私は0123にそれを挿入できませんでしたフィールド。私は、何かシンプルなものがあると確信しています。これらの関係を挿入するためには何が必要ですか?

答えて

3

まずはuser_idのような外部キーは、あなたが持っているようにusers_idではなく、このように正確に名前を付ける必要があります。 MyApp.Post.changesetの外観も確認してください。おそらく、この新しいパラメータをoptionalのパラメータのリストに追加するべきです。それ以外の場合は、この関数によって無視されます。

+0

このパラメータを 'optional'リストに含める方法の例を含めることができますか? –

+0

もちろん、 'cast'に入れたものはあなたのオプションリストです:https://github.com/learnphoenixtv/blog/blob/master/lib/blog/post.ex#L16。 Phoenix 1.2のモジュール属性を使用して 'optional'と' required'パラメータを指定し、 'cast'と' validate_required'でそれぞれこれらのリストを使用する方法を優先します。 – PatNowak

関連する問題