2016-07-12 8 views
2

サブ文書のリストが埋め込まれた文書があります。 Ectoを使用して埋め込みリストの特定のドキュメントを更新/変更するにはどうすればよいですか?埋め込みリスト内の1つのサブ文書をEctoで更新するには?

defmodule MyApp.Thing do 
    use MyApp.Model 

    schema "things" do 
    embeds_many :users, User 
    end 
end 


defmodule MyApp.User do 
    use MyApp.Model 

    embedded_schema do 
    field :name, :string 
    field :email, :string 
    field :admin, :boolean, default: false 
    end 
end 

defmodule MyApp.Model do 
    defmacro __using__(_) do 
    quote do 
     use MyApp.Web, :model 
     @primary_key {:id, :binary_id, autogenerate: true} 
     @foreign_key_type :binary_id # For associations 
    end 
    end 
end 

答えて

0

私のソリューションは、これまでのところ、私は事に、このリストを更新し、作る1人のユーザのチェンジの新リストや他のユーザーが、その後put_embedしたいもの以外のすべてのユーザーのリストを生成することです。それは動作しますが、これにはより洗練された解決策が必要であるように感じます。

user  = Enum.find(thing.users, fn user -> user.id == user_id end) 
other_users = Enum.filter(thing.users, fn user -> user.id != user_id end) 
user_cs  = User.changeset(user, %{email: email}) 
users  = [user_cs | other_users] 

thing 
|> Ecto.Changeset.change 
|> Ecto.Changeset.put_embed(:users, users) 
|> Repo.update 

EDIT:私はこの "ソリューション" の深刻な落とし穴を発見しました。手を触れられていないユーザーも同様に更新されます。これは、一致するコール(競合状態)の問題となります。したがって、別の解決策が必要です。

関連する問題