5

Sup,我正在学习 Ecto,我正在尝试将具有关联的记录插入到另一个表中。它有点工作,因为正在插入记录但外键字段为空。

代码:

parent = Repo.get(Hangman.MasterCat, parent_id)
changeset = build(parent, :categories)
  |> Category.changeset( params)
IO.inspect(changeset)

if changeset.valid? do
  Repo.insert(changeset)
  json conn, ResponseUtils.jsonResponse(true)
else
  json conn, ResponseUtils.jsonResponse(false,["parents doesn't exist"])
end

检查变更集

%Ecto.Changeset{action: nil, changes: %{name: "Kategory 1"}, constraints: [],
 errors: [], filters: %{},
 model: %{__meta__: #Ecto.Schema.Metadata<:built>, __struct__: Hangman.Category,

   id: nil, inserted_at: nil, master_cat_id: 1,
   mastercat: #Ecto.Association.NotLoaded<association :mastercat is not loaded>,

   mastercat_id: nil, name: nil, updated_at: nil,
   words: #Ecto.Association.NotLoaded<association :words is not loaded>},
 optional: [], opts: [], params: %{"name" => "Kategory 1"}, repo: nil,
 required: [:name],
 types: %{id: :id, inserted_at: Ecto.DateTime, mastercat_id: :id, name: :string,

   updated_at: Ecto.DateTime,
   words: {:assoc,
    %Ecto.Association.Has{cardinality: :many, defaults: [], field: :words,
     on_cast: :changeset, on_delete: :nothing, on_replace: :raise,
     owner: Hangman.Category, owner_key: :id, queryable: Hangman.Word,
     related: Hangman.Word, related_key: :category_id}}}, valid?: true,
 validations: []}

我可以看到出于某种奇怪的原因,它将父 ID 分配给字段 master_cat_id 而不是 mastercat_id。

任何帮助深表感谢。 https://github.com/Hajto/hangmanelixir

4

1 回答 1

6

外键是由association_key/2(故意未记录的)Ecto.Association模块中的函数从模块名称中推断出来的:

iex(1)> Ecto.Association.association_key(User, :id)
:user_id
iex(3)> Ecto.Association.association_key(FooBar, :id)           
:foo_bar_id
iex(5)> Ecto.Association.association_key(MasterCat, :id)
:master_cat_id

更改belongs_to/3模式以使用显式外键字段名称:

   schema "categories" do
    field :name, :string

    has_many :words, Hangman.Word
    belongs_to :mastercat, Hangman.MasterCat, foreign_key: :master_cat_id

    timestamps
  end
于 2015-10-17T14:36:32.507 回答