gchase
Build_assoc problem
This is my function which i am using to build an association with a tag (which is just a string) and a post.
defp save_to_tag_database(tag, post_id) do
tag_params = %{tag: tag |> String.trim}
post = Repo.get!(Post, post_id)
changeset = post
|> build_assoc(:tags)
|> Tag.changeset(tag_params)
|> Repo.insert
end
It ends up saving the tag but not the post_id
My schema is that each tag belongs_to :posts, Project.Post and each post has_many :tags, Project.Tag
My migration file current has table(:tags) :post_id, :integer, it used to be :post_id, references(:posts)
I have been trying to do this for a while now but can’t figure it out.
Most Liked
jwarlander
Great! Would you mind sharing, for anyone else who might end up reading this in the future with a similar problem? ![]()
gchase
Essentially what happened was that I didn’t include :post_id in my cast. Ended up making it like cast(params, [:tag, :post_id]). Also my belong_to :posts, Project.Post was wrong. It should be belongs_to :post, Project.Post. All in all I won’t forget these little mistakes anymore!
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
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









