Adding current user information to a message in the Phoenix Framework

I am switching from Rails to Phoenix and moving on to a problem that I cannot find the answer to.

I have user authentication installed (by checking for @current_user in a private authentication function).

I also have a Post model / controller / view (scaffold for acquaintances w Rails).

I would like to automatically populate the Post field with the @current_user identifier when submitting the form (each message will belong to the user) without the form field that the user must fill out.

In Rails, this is pretty simple ... something similar is added to the post controller creation action:

@post.user = current_user.id 

How do I do this with the Phoenix Framework / Elixir?

Here's the create action in my PostController

  def create(conn, %{"post" => post_params}) do changeset = Post.changeset(%Post{}, post_params) case Repo.insert(changeset) do {:ok, _project} -> conn |> put_flash(:info, "Please check your email inbox.") |> redirect(to: page_path(conn, :thanks)) {:error, changeset} -> render(conn, "new.html", changeset: changeset) end end 

Should this type of logic be executed in a controller or model? or is there a good way to do this in a view (without using a hidden field that is not safe).

Solution (thanks to Gazler):

  def create(conn, %{"post" => post_params}) do current_user = conn.assigns.current_user changeset = Post.changeset(%Post{user_id = current_user.id}, post_params) case Repo.insert(changeset) do {:ok, _project} -> conn |> put_flash(:info, "Please check your email inbox.") |> redirect(to: page_path(conn, :thanks)) {:error, changeset} -> render(conn, "new.html", changeset: changeset) end end 
+5
source share
1 answer

You can use the following:

 current_user = conn.assigns.current_user changeset = Post.changeset(%Post{user_id: current_user.id}, post_params) 

Or use Ecto.build_assoc / 3 :

 current_user = conn.assigns.current_user changeset = Ecto.build_assoc(current_user, :posts, post_params) 

Suppose you have current_user in conn.assigns .

+10
source

Source: https://habr.com/ru/post/1245987/


All Articles