Ecto关系,不插入外键ID

时间:2015-10-17 14:30:22

标签: elixir phoenix-framework ecto

燮, 我正在学习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

1 个答案:

答案 0 :(得分:5)

外键是由(故意未记录的)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