Search code examples
elixirphoenix-frameworkecto

How to update all models assigned to model?


TimeStamp belongs to Card, Card has_many TimeStamps, in my case when user check 'assing_card' then How to assign to the user all other TimeStamps through card.time_stamps? All my attempts are after if assing_card do in TimeStampController:

def update(conn, %{"time_stamp_id" => time_stamp_id, "user_id" => user_id, "assing_card" => assing_card} = params) do
  time_stamp = Repo.get!(TimeStamp, time_stamp_id) |> Repo.preload [:user, :card]

  time_stamp = %{time_stamp | user_id: String.to_integer(user_id)}

  if assing_card do
    time_stamps = time_stamp.card
      |> Repo.preload(:time_stamps)
      |> Map.get(:time_stamps)# here I have list with time_stamps ... How to |> Repo.update_all(set: [user_id: String.to_integer(user_id)]) ?
  ... 

Solution

  • Instead of preloading the :time_stamps, would updating the TimeStamp rows directly accomplish what you are wanting to do?

    Ecto.Model.assoc(time_stamp.card, :time_stamps)
      |> Repo.update_all(set: [user_id: String.to_integer(user_id)])