2017-10-11 6 views
1

誰かが投稿を更新すると、ニュースフィードテーブルにエントリが追加されるブログアプリケーションがあります。次のようにPostNewsfeedスキーマは、次のとおりです。ここでEcto.Multiでレコードを更新する際の問題

mix phx.new.json Content Post posts title:string content:string 
mix phx.new.json Content Newsfeed newsfeeds message:string 

は、ラッパー関数である:

def updateContent(%{id: id, content: content}, _info) do 
    post = Repo.get(post, id) 
    Content.update_content_and_add_to_newsfeed(post, %{id: id, content: content}) 
    end 

そしてここでは、コンテンツのコンテキスト内のロジックである:ここで

def update_content_and_add_to_newsfeed(post, %{id: id, content: content}) do 
    multi = 
     Multi.new 
     |> Multi.update(:post, update_post(post, %{content: content})) 
     |> Multi.insert(:newsfeed, %Newsfeed{message: "post updated"}) 

    case Repo.transaction(multi) do 
     {:ok, %{post: post}} -> 
     {:ok, post} 
     {:error, _} -> 
     {:error, "Error"} 
    end 
    end 

はupdate_postです機能:

def update_post(%Post{} = post, attrs) do 
    post 
    |> Post.changeset(attrs) 
    |> Repo.update() 
    end 

私は、このコードは、データベース内のコンテンツの更新を実行しますが、何のニュースフィード項目が挿入されません、と私は、コンソールでこのエラーメッセージが表示されたら:

Server: localhost:4000 (http) 
Request: POST /graphiql 
** (exit) an exception was raised: 
    ** (FunctionClauseError) no function clause matching in Ecto.Multi.update/4 

任意のアイデアはどのようにこの問題を解決するために?私は、Absinthe v2.2.6と 1.3を使用しています。

+1

{:_、エラーを}' '代わりの{:エラー、_、_、_}'。 'update_post'メソッドのコードを投稿することもできますか? – Sheharyar

+0

上記の更新を参照 –

答えて

1

あなたのMulti.update/4の呼び出しは、チェンジセットが必要なので間違っています。代わりに、Postをトランザクション外に更新し、更新結果を渡しています。

トランザクションの目的は、エラーが発生した場合にロールバックすることです。つまり、失敗した場合は、すべての変更を元に戻す必要があります(これはあなたのケースでは起こりません)。


あなたupdate_post方法を削除し、代わりにちょうどチェンジを渡す:

multi = 
    Multi.new 
    |> Multi.update(:post, Post.changeset(post, %{content: content})) 
    |> Multi.insert(:newsfeed, %Newsfeed{message: "post updated"}) 

また、Ecto.Multiトランザクションが失敗した場合、それは4要素のエラータプルではなく、通常の2要素の1を返します。 。したがって、このようなあなたのcase文を変更します。これは、あなたが `使用して行う必要があります

case Repo.transaction(multi) do 
    {:ok, %{post: post}} -> 
    {:ok, post} 
    {:error, _op, _value, _changes} -> 
    {:error, "Error"} 
end 
関連する問題