Nullstrike
How to pass a changeset with put_assoc in Phoenix Form tag
How to pass a changeset in phoenix form?
I use put_assoc function as I get the user struct from the cureent user that are assign to session.
Here’s a snippet from the controller:
def new(conn, _params) do
changeset = Blog.change_post(%Post{})
render(conn, "new.html", changeset: changeset)
end
But I get this error
key :user not found in: %{}
Here’s my post changeset:
def changeset(post, attrs) do
post
|> cast(attrs, [:title, :content, :is_published])
|> validate_required([:title, :content])
|> put_slug()
|> put_assoc(:user, attrs.user)
end
Marked As Solved
idi527
![]()
It seems like you are passing an empty attrs map in Blog.change_post(%Post{}) (the contents of the change_post/1 might be helpful), and in your changeset/2 you expect it to have a :user.
To avoid the error, try replacing your current change_post/1 with
def change_post(post) do
Ecto.Changeset.change(post)
end
then the changeset/2 won’t be called.
Also Liked
chensan
Since you are using Blog context in your code, I would suggest putting put_assoc in your context instead of messing your changeset/2, for example, you can define change_post/2 as bellow:
def change_post(%User{} = user, %Post{} = post) do
Post.changeset(post, %{})
|> put_assoc(:user, user)
end
Then in your new action:
def new(conn, _) do
changeset = Blog.change_post(conn.assigns.current_user, %Post{})
render(conn, "new.html", changeset: changeset)
end
Nullstrike
Yes it’s already been solved, I just forgot to marked this a solved.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









