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

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.

Figured it out thanks to the help of gjaldon!

Great! Would you mind sharing, for anyone else who might end up reading this in the future with a similar problem? :slight_smile:

1 Like

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!

1 Like

Thanks, saved me an hour of work :slight_smile: