Elixir 在Ecto中添加关系(Phoenix 1.3)
我正在努力建立一对多的关系。用户可以创建任意数量的帖子。凤凰城1.3,星外2.2.1Elixir 在Ecto中添加关系(Phoenix 1.3),elixir,phoenix-framework,ecto,Elixir,Phoenix Framework,Ecto,我正在努力建立一对多的关系。用户可以创建任意数量的帖子。凤凰城1.3,星外2.2.1 #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: fals
#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
当我运行迁移和种子时,我在查询帖子时会看到以下内容:
%MyApp.Post{__meta__: #Ecto.Schema.Metadata<:loaded, "resources">,
content: "content", title: "title",
users: #Ecto.Association.NotLoaded<association :users is not loaded>,
users_id: nil}
%MyApp.Post{{uuuuuu meta}:{35; exto.Schema.Metadata,
内容:“内容”,标题:“标题”,
用户:#exto.Association.NotLoaded,
用户\u id:nil}
尽管我成功地获取了用户id,但我无法将其插入
users\u id
字段。我确信我遗漏了一些简单的东西,我必须做些什么才能插入这些关系 首先-像user\u id
这样的外键应该以这种方式命名,而不是像您这样的users\u id
。
另外,请检查您的
MyApp.Post.changeset
的外观。或者,您应该在可选允许参数列表中添加此新参数。否则,此函数将忽略此参数。您能否提供一个示例,说明如何将此参数包括在可选列表中?当然,您放入强制转换中的是您的可选列表:。我预告了Phoenix 1.2中的方式,在那里您使用模块属性指定可选
和必需
参数,然后分别在cast
和validate\u required
中使用这些列表。
#seeds.exs
MyApp.User.changeset(%MyApp.User{}, %{
email: "me@myapp.com",
handle: "me",
password_hash: Comeonin.Bcrypt.hashpwsalt("me")})
|> MyApp.Repo.insert!
user = MyApp.Repo.get_by(MyApp.User, email: "me@myapp.com")
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}