thiagomajesk

thiagomajesk

How to associate an existing record using belongs_to with Ecto?

Hello everyone!

Something happened at work today and it kinda got me off-guard because I was expecting different behavior from Ecto. What happened is: I was trying to insert a record with a given association that already existed in the database without casting the foreign key directly.

For example:

schema "post" do
  field :title, :string
  field :body, :string
end
schema "category" do
  field :name, :string
  field :description, :string
end
schema "category_post" do
  belongs_to :post, Post
  belongs_to :category, Category
  field :remarks, :string
end

def changeset(category_post, attrs) do
  post
  |> cast(attrs, [:remarks])
  |> cast_assoc(:post)
  |> cast_assoc(:category)
  |> validate_if_posts_has_the_right_amount_of_comments() # needs the retrieved post
  |> validate_if_category_has_the_right_amount_of_followers() # needs the retrieved category
end

And then, trying to create a “category_post” with its relationship:

def create_category_post(attrs, post_id, category_id) do
  post = Posts.get_post!(post_id)
  category = Categories.get_category!(category_id)

  attrs = Map.merge(attrs, %{category: category, post: post})
   
  %CategoryPost{}
  |> CategoryPost.changeset(attrs)
  |> Repo.insert()
end

Is this even possible? I noticed that for this case Ecto always tries to insert a new “post”/ “category” if I use cast_assoc/3.

Most Liked

kokolegorille

kokolegorille

If the record already exists, You should use put_assoc instead.

But for this use case, I would use build_assoc.

Sleepful

Sleepful

trying to update my own code but I can’t so posting it again, this is clearer:

      schema "table_table" do
        belongs_to :related_post,
          Post,
          [foreign_key: :post_id, define_field: false]

        field :post_id, :integer
          # and you can add the following to opts if you want
          # the field and the column on the DB to have 
          # different names:
          # [source: :"table_column_id"]

      end

      def changeset(schema, attrs) do
        schema
        |> cast(attrs, [:post_id])
        |> cast_assoc(:related_post)
      end

Where Next?

Popular in Questions Top

beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> somethi...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
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
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: <h1>Create Post</h1> <%= ...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New

Other popular topics Top

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
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 127089 1222
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement