Put_assoc/cast_assoc for belongs_to relationship

# Part of my seed script:

new_item = %{ name: name,
                         category: cat_id #This is an integer that matches the Category primary key and *can be null*
                }
   
        changeset = Item.changeset(%Frobl.Item{}, new_item)
      
       Repo.insert!(changeset)


    def changeset(%Frobl.Item{} = item, params \\ %{}) do
   
        item
        |> cast(params, [:name, :text, :map_thumb, :map_full,
                        :address, :city, :state, :postal_code,
                        :country_code, :county, :geokey, 
                        :hidden, :views, :allow_map, :allow_pm, :allow_chat, :rating, :expires])
        |> validate_required([:name])
        |> cast_assoc(:category)
  
    end

I’m new to elixir and I’ve been really struggling trying to get this to work. Basically I just want to seed records that can have a category id but may not.

The most common error I’m getting:
%{category: [{"is invalid", [type: :map]}]}

My column definition from the database migration:
add :category, references(:categories, on_delete: :nilify_all)

Any help/guidance you can spare I would appreciate it, thank you in advance!

So I think that I’ve figured out that :category needs to be a map (or nil) of the referenced category, but the pain I’m having now is it’s trying to insert the category into the table (eg. adding the association) instead of just saving the value of the foreign key.

This is pretty struggly :frowning2:

I don’t think you have to use cast_assoc if all you are passing in is category_id. Just use cast(attrs, [:category_id, ...other fields]). But I might be misunderstanding your problem.

Thank you very much! Yes, I pass it as category_id and it worked like a boss!