Need help assigning users to posts on Twitter-like application (Chirp)

I’ve been learning Phoenix and so I followed a tutorial to create a Twitter-like application ( ) and went by the Programming Phoenix book (especially chapter 5) to integrate logins and sessions into my application. However, posts are always defaulted to the first user (the default on post.ex is 1) and I have no idea how to assign it to the current session user.

My question is: how would I assign a user to a post rather than use the default one? Could provide more details if needed, but pretty much all of my code is in the resources I said above.


Can you push your project to github? It would make it easier for us to better understand the issue. Here! I assume changes must be made to create_post to correctly assign the current session’s user to the post creator.

I’ve opened a PR with the changes that I think should help you achieve your goal, but I haven’t actually tried them out locally (so they might not work :sweat_smile:).

Hey, it worked, thanks a ton! I had to adapt a bit but yeah. It only broke the /posts/ route if I’m logged out, any idea on how to fix it? The error is “no function clause matching in RumblWeb.PostLive.Index.mount/3”, maybe it can’t find an user. I could also redirect them to the root route but I’m not sure how yet.

If there’s not a user_id in the session that is mounted the pattern won’t match.

There are two options, you can pass just the session to the mount like

def mount(_params, session, socket) do

Or you can add another mount function just below the original one that will match when there’s no user_id in the session

  @impl true
  def mount(_params, %{"user_id" => user_id}, socket) do
    #{:ok, assign(socket, :posts, list_posts())}
    user = Repo.get(Rumbl.User, user_id)
    socket = assign(socket, current_user: user)
    if connected?(socket), do: Timeline.subscribe()
    {:ok, assign(socket, :posts, list_posts()), temporary_assigns: [posts: []]}

  # Here you handle your logic for redirect or
  # whatever you want
  def mount(_params, _session, socket) do
    {:ok, socket}