I am trying to duplicate an existing entry with a different :belongs_to value but am receiving the following error:
** (ArgumentError) cannot change belongs_to association item_type
because there is already a change setting its foreign key item_type_id
to 1
Here is the relevant code:
Migrations:
create table(:item_type) do
add :name, :text
end
create table(:item) do
add :name, :text
add :item_type_id, references(:item_type, on_delete: :nothing)
end
Schema:
schema "item_type" do
field :name, :string
has_many :items, Item
end
schema "item" do
field :name, :string
belongs_to :item_type, ItemType
end
And the get/insert code that generates the error:
def changeset(item, params \\ %{}) do
item
|> cast(params, [:name, :item_type_id])
|> validate_required([:name])
end
def get_insert(attrs) do
Repo.get(Item, attrs.id)
|> Repo.preload(:item_type)
|> Item.changeset(%{item_type_id: attrs.item_type_id})
|> Repo.insert()
end
The changeset and changeset.data generated by the above get_insert function:
#Ecto.Changeset<
action: nil,
changes: %{item_type_id: 1},
errors: [],
data: #Bevdb.Data.Item<>,
valid?: true
>
%Bevdb.Data.Item{
__meta__: #Ecto.Schema.Metadata<:loaded, "item">,
id: 1,
item_type: %Bevdb.Data.ItemType{
__meta__: #Ecto.Schema.Metadata<:loaded, "item_type">,
id: 2,
items: #Ecto.Association.NotLoaded<association :items is not loaded>,
name: "Type One"
},
item_type_id: 2,
name: "Item One"
}
Any help is appreciated. I am new to Elixir and struggling a bit with associations.
Let me know if I can provide any additional information.
Thanks!