Ecto:如何验证belongs_to关联的存在?

时间:2017-04-13 12:04:00

标签: elixir phoenix-framework ecto

defmodule ParrotApi.Meetup do

    schema "meetups" do
      field :timestamp, :integer
      belongs_to :topic, ParrotApi.Topic

      timestamps()
    end


    @required_fields ~w(timestamp)

    def changeset(struct, params \\ %{}) do
      struct
      |> cast(params, @required_fields)
      |> cast_assoc(:topic, required: true)
      |> validate_required(@required_fields)
    end

end

但是当我在测试中这样做时:

%Meetup{timestamp: future_time, topic_id: topic.id} |> Repo.insert

它没有通过错误:

iex(10)> %Meetup{timestamp: 123123} |> Repo.insert
[debug] QUERY OK db=0.3ms
begin []
[debug] QUERY OK db=1.3ms
INSERT INTO "meetups" ("timestamp","inserted_at","updated_at") VALUES ($1,$2,$3) RETURNING "id" [123123, {{2017, 4, 13}, {12, 3, 24, 644065}}, {{2017, 4, 13}, {12, 3, 24, 644074}}]
[debug] QUERY OK db=1.6ms
commit []
{:ok,
 %ParrotApi.Meetup{__meta__: #Ecto.Schema.Metadata<:loaded, "meetups">, id: 6,
  inserted_at: ~N[2017-04-13 12:03:24.644065], timestamp: 123123,
  topic: #Ecto.Association.NotLoaded<association :topic is not loaded>,
  topic_id: nil, updated_at: ~N[2017-04-13 12:03:24.644074]}}
iex(11)>

如何确保仅使用topic_id进行Meetup?

1 个答案:

答案 0 :(得分:1)

尝试将atom用于字段而不是字符串。我认为required_fields想要原子。此外,如果要添加topic_id,还需要列出该字段。只需更改为@required_fields ~w(timestamp topic_id)a即可。也可以在required_fields来电后立即致电cast