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にそれを挿入できませんでしたフィールド。私は、何かシンプルなものがあると確信しています。これらの関係を挿入するためには何が必要ですか?
このパラメータを 'optional'リストに含める方法の例を含めることができますか? –
もちろん、 'cast'に入れたものはあなたのオプションリストです:https://github.com/learnphoenixtv/blog/blob/master/lib/blog/post.ex#L16。 Phoenix 1.2のモジュール属性を使用して 'optional'と' required'パラメータを指定し、 'cast'と' validate_required'でそれぞれこれらのリストを使用する方法を優先します。 – PatNowak