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

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
Tee
can someone please explain to me how Enum.reduce works with maps
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
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
New

Other popular topics Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
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

We're in Beta

About us Mission Statement