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에 삽입 할 수 없습니다.필드. 내가 누락 된 단순한 것이 있다고 확신합니다. 이러한 관계를 삽입하려면 어떻게해야합니까?
이 매개 변수를 '선택 사항'목록에 포함시키는 방법에 대한 예를 포함시킬 수 있습니까? –
물론,'cast'에 넣은 것은 선택 목록입니다 : https://github.com/learnphoenixtv/blog/blob/master/lib/blog/post.ex#L16. Phoenix 1.2에서 모듈 속성을 사용하여'optional' 및'required' 매개 변수를 지정하는 방식으로 preffer를 작성한 다음이 목록을 각각'cast' 및'validate_required'에서 사용합니다. – PatNowak