Nullstrike

Nullstrike

When updated a table the associated table is removed

Hello,

Why is that my update function nillify the association entity.

I have two entities: Post and User

So create function controller is like this:

def create(conn, %{"post" => post_params}) do
  current_user = get_session(conn, :current_user)
  post_params = Map.merge(%{"user" => current_user}, post_params)
  case Blog.create_post(post_params) do
    {:ok, post} ->
      conn
       |> put_flash(:info, "Post created successfully.")
       |> redirect(to: Routes.post_path(conn, :show, post))
    {:error, %Ecto.Changeset{} = changeset} ->
      render(conn, "new.html", changeset: changeset)
  end
end

which associates the user to the post.

Post schema

def changeset(post, attrs) do
    post
    |> cast(attrs, [:title, :content, :is_published])
    |> validate_required([:title, :content])
    |> put_slug()
    |> put_assoc(:user, attrs["user"])
end

My problem is when updating a post the user associated with the post gets nillify:

UPDATE "posts" SET "content" = $1, "user_id" = $2, "updated_at" = $3 WHERE "id" = $4 ["Loading...", nil, ~N[2018-12-02 13:35:59], 4]

controller:

def update(conn, %{"id" => id, "post" => post_params}) do
    post = Blog.get_post!(id)
      
    case Blog.update_post(post, post_params) do
      {:ok, post} ->
        conn
        |> put_flash(:info, "Post updated successfully.")
        |> redirect(to: Routes.post_path(conn, :show, post))

      {:error, %Ecto.Changeset{} = changeset} ->
        render(conn, "edit.html", post: post, changeset: changeset)
    end
  end

My question is how to retain the user associated to the post?

Should I write a new params that Map.merge the post_params and the current_user which is the same as I did in the create function?

Please ask clarification if my explanation is not clear. Thank you.

Marked As Solved

kokolegorille

kokolegorille

I forgot to mention I use the same principle for create.

  def create_post(user, attrs \\ %{}) do
    %Post{}
    |> Post.changeset(attrs)
    |> put_user(user)
    |> Repo.insert()
  end

Also Liked

kokolegorille

kokolegorille

Fom Ecto Changeset documentation nil value can be used to remove association with put_assoc…

A better way is to remove put_assoc from your changeset…

def changeset(post, attrs) do
    post
    |> cast(attrs, [:title, :content, :is_published])
    |> validate_required([:title, :content])
    |> put_slug()
end

and put this in your context.

  def change_post(user, post) do
    post
    |> Post.changeset(%{})
    |> put_assoc(:user, user)
  end

Then use change_post inside the new action, and update_post with the update action. change_post will use put_assoc, but not update_post.

kokolegorille

kokolegorille

Yes, but it’s just a call to put_assoc…

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&query=perfume&page=2, I would like to get: ...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41539 114
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

We're in Beta

About us Mission Statement