Hello guys,
Sorry for disturbing you again but I’m facing an issues that I cannot understand on my own.
I’m trying to create a image gallery api that handles images associated with categories and tags,
right now I’m focused on the association between the images and the categories and when I’m trying to send a image with a category id the image enitty is created but not associated with the category:
phoenix_1 | [info] POST /api/image
phoenix_1 | [debug] Processing with ApiAppWeb.ImageController.create/2
phoenix_1 | Parameters: %{"image" => %{"category_id" => 1, "description" => "This is a test image", "image" => "mylovelywife.png", "name" => "i1"}}
phoenix_1 | Pipelines: [:api]
phoenix_1 | [debug] QUERY OK db=2.9ms queue=0.1ms idle=9349.5ms
phoenix_1 | INSERT INTO "image" ("description","image","name","inserted_at","updated_at") VALUES ($1,$2,$3,$4,$5) RETURNING "id" ["This is a test image", "mylovelywife.png", "i1", ~N[2020-04-20 23:37:57], ~N[2020-04-20 23:37:57]]
phoenix_1 | [info] Sent 201 in 7ms
Here is my schema for my categories:
schema "category" do
field :name, :string
has_many :image, ApiApp.Images.Image
timestamps()
end
@doc false
def changeset(categories, attrs) do
categories
|> cast(attrs, [:name])
|> validate_required([:name])
|> unique_constraint(:name)
|> validate_length(:name, max: 60, count: :codepoints)
end
And the schema for the images :
schema "image" do
field :description, :string
field :image, :string
field :name, :string
belongs_to :category, ApiApp.Images.Categories, foreign_key: :category_id
timestamps()
end
@doc false
def changeset(image, attrs) do
image
|> cast(attrs, [:name, :description, :image])
|> validate_required([:name, :description, :image])
|> foreign_key_constraint(:category_id,
name: :image_category_id_fkey,
message: "Category not found!"
)
end
Also in my create_image method I’ve putted the changest’s cast_assoc method:
def create_image(attrs \\ %{}) do
%Image{}
|> Image.changeset(attrs)
|> cast_assoc(:category, with: &Category.changeset/2)
|> Repo.insert()
end
If anyone got an idea of what I’m doing wrong It would be great to hear !
Thanks a lot for your time and help guys.