JackMaarek

JackMaarek

Elixir association help

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.

Most Liked

axelson

axelson

Scenic Core Team

I think you might want to change your parameters from:
%{"image" => %{"category_id" => 1, "description" => "This is a test image", "image" => "mylovelywife.png", "name" => "i1"}}
to:
%{"image" => %{"category" => %{"id" => 1}, "description" => "This is a test image", "image" => "mylovelywife.png", "name" => "i1"}}

cast_assoc expects the embed to have nested params.

nickdichev

nickdichev

So, in your controller you have create/2 where you catch the happy path in the with clause. What I think is happening here is that you are actually getting a changeset error that isn’t being handled. The reason I think this is the case is because of the fallback controller function definition error.

You don’t have an else clause for the with so create/2 is just returning the {:error, changeset} of Repo.insert() in create_image/1. But, {:error, changeset} isn’t a valid %Plug.Conn{} struct – the expected return of your controller functions!

Since you’re not returning a %Plug.Conn{}, Phoenix tries to help you out and call your defined fallback controller ApiAppWeb.FallbackController. You are likely missing the function call(conn, {:error, changeset}) there (you might want to pattern match against the changeset against %Ecto.Changeset{} to avoid a catch all match…)

So you have a couple options to debug from here. You can define the fallback controller call/2 and inspect in there, or put an inspect in your changeset pipeline to see what’s going wrong. (The error is actually in the previous error you posted, at the very end of the line)

I know this is a lot so let me know if you have any questions! Also here’s the documentation on the fallback controller with good examples!

axelson

axelson

Scenic Core Team

If you’re trying to debug what’s happening you should use IO.inspect instead of IO.puts:

def call(conn, {:error, changeset}) do
  IO.inspect(changeset, label: "changeset")
  IO.inspect(conn, label: "conn")
end

More info at:

Where Next?

Popular in Discussions Top

mikl
I wanted to capitalize a string, and tried using String.capitalize(). That generally works well, until you try to capitalize a word like...
New
Rustixir
Hi everyone, im working on find best language/framework/system for high concurrency, high performance and stable performance after wor...
New
Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
New
WolfDan
After doing a port from a c++ library to my project in phoenix I’ve seen that I need a faster way to run this algorithm and I found this ...
New
tmbb
This is a post to discuss the new Phoenix LiveView functionality. From Chris’s talk, it appears that they generate all HTML on the serve...
342 18146 126
New
PragTob
Hey everyone, this has been brewing in my head some time and it came up again while reading Adopting Elixir. GenServers, supervisors et...
New
jer
I’ve been using umbrellas for a while, and generally started off (on greenfield projects at least) by isolating subapps based on clearly ...
New
PragTob
Hey everyone, this has been on my mind for some time and I’d love your input on it! TLDR: I feel like maps are superioer for storing and...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New

Other popular topics Top

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 47930 226
New
Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 126479 1222
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement