这是我的工厂:(using the ex_machina package)
def question_factory do
%Question{
active: true,
type: "NBA",
description: "player points",
reserved: %{
information: %{
game_id: Ecto.UUID.generate,
player_id: Ecto.UUID.generate,
player_name: "Lebron James"
},
inputs: [
%{
type: "text",
label: "Player Points",
}
]
}
}
end
schema "questions" do
field(:active, :boolean)
field(:type, :string)
field(:description, :string)
embeds_one(:reserved, Statcasters.Questions.Reserved)
timestamps()
end
embedded_schema do
field(:information, :map)
field(:inputs, {:array, :map})
end
这是我的测试设置:
question = insert(:question, reserved: %{ information: %{player_name: "steve"}})
在此示例中,我想only
更新player_name
映射的reserved
。但是当我使用上述设置时,问题结构看起来像这样:
%MyApp.Question{
__meta__: #Ecto.Schema.Metadata<:loaded, "questions">,
active: true,
description: "player points",
id: 125,
inserted_at: ~N[2018-08-27 14:47:42.075169],
reserved: %MyApp.Questions.Reserved{
information: %{player_name: "steve"},
inputs: nil
},
type: "NBA",
updated_at: ~N[2018-08-27 14:47:42.075182]
}
我希望它看起来像这样:
%MyApp.Question{
__meta__: #Ecto.Schema.Metadata<:loaded, "questions">,
active: false,
description: "player points",
id: 122,
inserted_at: ~N[2018-08-27 14:39:52.672051],
reserved: %MyApp.Questions.Reserved{
information: %{
game_id: "1ab95979-329a-488c-9d5f-22bed4f2b985",
player_id: "07cc1588-68eb-43b6-afa6-483fa3005cb2",
player_name: "Steve"
},
inputs: [%{label: "Player Points", type: "text"}]
},
type: "NBA",
updated_at: ~N[2018-08-27 14:39:52.672058]
}
同样,问题在于它正在替换reserved
中的所有值,我只想更改player_name
,如何使用elixir
和ex_machina
来实现?感谢您的帮助。
答案 0 :(得分:1)
您当前明确地告诉ex_machina
按照指定设置reserved
。当需要更新记录时,应ExMachina.build/2
对其进行记录,更新并保存。或者,ExMachina.Ecto.insert/2
支架,然后对其进行更新,但这不是ex_machina
想要的。
也就是说,以下应该起作用。
:question
|> build()
|> put_in(~w|reserved information player_name|a, "steve")
|> insert()
有关详细信息,请参见Flexible Factories with Pipes。