Elixir 如何验证是否存在关联?
但当我在测试中这样做时:Elixir 如何验证是否存在关联?,elixir,phoenix-framework,ecto,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 \\ %{}) d
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
[调试]查询OK db=0.3ms
开始[]
[调试]查询OK db=1.3ms
在“meetups”(“timestamp”,“inserted_at”,“updated_at”)中插入值($1,$2,$3),返回“id”[123123,{2017,4,13},{12,3,24,644065},{2017,4,13},{12,3,24,644074}]
[调试]查询OK db=1.6ms
提交[]
{好的,
%ParrotApi.Meetup{{uuuuu meta}:}exto.Schema.Metadata,id:6,
插入地址:~N[2017-04-13 12:03:24.644065],时间戳:123123,
主题:#exto.Association.NotLoaded,
主题id:nil,更新地址:~N[2017-04-13 12:03:24.644074]}
iex(11)>
如何确保会议仅在主题id出现的情况下进行?尝试在字段中使用原子,而不是字符串。我想我们需要原子。此外,如果要添加主题id,还需要列出该字段。只需更改为
@required\u fields~w(时间戳主题\u id)a
。另外,请尝试在调用cast
后立即调用required\u字段
。如果直接创建结构并将其发送到数据库,则不会运行EXTO验证。为此,您需要将此约束添加到数据库字段。对不起,我是新加入Ecto的。有没有其他方法可以创建聚会?我以为这就是它的语法是的,Meetup.changeset(%Meetup{},%%{timestamp:123123})|>Repo.insert
.Hm它告诉我,**(ArgumentError)无法将参数'timestamp'转换为原子,'timestamp'不是模式字段
nvm修复了它!它不喜欢我的模型中的@required\u字段。谢谢
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)>