2016-07-15 15 views
5

how to ビルドアソシエーション ectoの新しいmany_to_manyフィーチャーを使用して_many_to_many_関係を持つ2つのテーブルの間で使用しますか?Many Manyアセンブリーをビルドして挿入する方法

私は、組織からユーザーへの一対多の関係を持っている:

organization = Organization.shortcode_changeset(%Organization{}, org_field) 
organization = organization |> Repo.insert! 
organization |> build_assoc(:users) 

私は、ユーザーとグループの間many_to_manyでこれを行うことができますどのように

%User{__meta__: #ecto.Schema.Metadata<:built, "users">,......} 

user = Repo.preload(user, [:organization, :usergroup]) 

を与えますか?ここで

答えて

1

あなたには、いくつかの組織名組織を持っていると仮定し、あなたとあなたの間の関連を構築したいユーザ名userは、チェンジセット内の関連付けを作成するために以下のステップを踏みます。

changeset = Repo.preload(org, :users) # load the :users for the org 
|> Organization.changeset(%{}) # somehow generate a changeset with no changes 
|> Ecto.Changeset.put_assoc(:users, [user]) # creates the association 

あなたがしなければならないことは、いつものようにチェンジセットを適用することだけです。 すなわち

Repo.update(changeset)