Ecto build_assoc / 3与定义的外键不匹配?

时间:2017-04-22 20:42:25

标签: elixir phoenix-framework ecto

我有以下两个模型,async function getFeed(token) { let feedItems = [], hasNext = true, apiCall = '/me/feed'; while (hasNext) { await new Promise(resolve => { FB.api(apiCall, {access_token: token}, (response) => { feedItems.concat(response.data); if (!response.paging.next) { hasNext = false; } else { apiCall = response.paging.next; } resolve(); }); }); } return feedItems; } getFeed().then((response) => { console.log(response); }); User。我正在尝试创建一个与用户具有外键关系的帖子。

我的架构:

Post

我的帖子创建方法:

@primary_key {:id, :binary_id, autogenerate: true}
schema "accounts_users" do
  field :username, :string
  field :email, :string
  field :password_hash, :string
  field :password, :string, virtual: true
  has_many :posts, Udia.Logs.Post

  timestamps(type: :utc_datetime)
end


@primary_key {:id, :binary_id, autogenerate: true}
schema "logs_posts" do
  field :title, :string
  field :content, :string
  belongs_to :creator, Udia.Accounts.User

  timestamps(type: :utc_datetime)
end

当我创建关联并检查帖子时,我希望将def create_post(user, attrs \\ %{}) do user |> Ecto.build_assoc(:posts, attrs) |> post_changeset(attrs) |> Repo.insert() end defp post_changeset(%Post{} = post, attrs) do IO.inspect post post |> cast(attrs, [:title, :content]) |> validate_required([:title, :content]) end 设置为creator_id,但这是我所看到的:

user_id

为什么User外键id与Post?

中定义的模式不匹配

1 个答案:

答案 0 :(得分:1)

刚解决它,我需要将我的模式更新为以下内容:

@primary_key {:id, :binary_id, autogenerate: true}
schema "accounts_users" do
  field :username, :string
  field :email, :string
  field :password_hash, :string
  field :password, :string, virtual: true

  # explicitly specify creator_id
  has_many :posts, Udia.Logs.Post, foreign_key: :creator_id

  timestamps(type: :utc_datetime)
end

@primary_key {:id, :binary_id, autogenerate: true}
schema "logs_posts" do
  field :title, :string
  field :content, :string

  # explicitly specify binary_id
  belongs_to :creator, Udia.Accounts.User, type: :binary_id

  timestamps(type: :utc_datetime)
end