2016-09-07 7 views
1

だから、エクトドキュメントの例のとおり、私は次のようしている:many_to_many関連でリレーションを追加および削除する方法は?

defmodule Post do 
    use Ecto.Schema 
    schema "posts" do 
    many_to_many :tags, Tag, join_through: "posts_tags" 
    end 
end 

defmodule Tag do 
    use Ecto.Schema 
    schema "tags" do 
    many_to_many :posts, Post, join_through: "posts_tags" 
    end 
end 

今までさまざまな方法どのようなもの:

a)は、既存の関連付け既存のタグで投稿する。

b)タグから既存の投稿との関連付けを解除します。

注ネストされたリソースを作成するのではなく、%Post{}tag_idという状況がありますが、それらの間の関連付けを作成または破棄したいと考えています。

答えて

4

ポストのためにすべてのタグをロードする必要はありませんそのうち、私は考えることができる2つの方法があります。

  1. は、例えば、結合テーブルのためのモジュールを作成します。 PostTag、次いで会合/ PostTag行を削除/作成することにより、解離:

    # web/models/post_tag.ex 
    defmodule PostTag do 
        use Ecto.Schema 
    
        @primary_key false 
        schema "posts_tags" do 
        belongs_to :post, Post 
        belongs_to :tag, Tag 
        end 
    end 
    
    # Create association 
    Repo.insert!(%PostTag(post_id: 1, tag_id: 2)) 
    
    # Remove association 
    Repo.get_by(PostTag, post_id: 1, tag_id: 2) |> Repo.delete! 
    
  2. 使用Repo.insert_all/2Repo.delete_all/2直接posts_tagsテーブルに:

    # Create assoication 
    Repo.insert_all "posts_tags", [%{post_id: 1, tag_id: 2}] 
    
    # Delete association 
    Repo.delete_all "posts_tags", [%{post_id: 1, tag_id: 2}] 
    
関連する問題