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
If the record already exists, You should use put_assoc instead.
But for this use case, I would use build_assoc.
1
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
1
Popular in Questions
I will often find my self writing things similar to:
case some_value do
nil -> something()
"" -> something()
_ -> somethi...
New
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
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
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
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
Hello everybody,
usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
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
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
Hi!
In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir?
Searched the docs for ip address and the web, no good results.
Thanks!
New
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
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
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
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
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
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
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
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...
New
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
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
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
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









