Creating belongs_to and has_many Ecto associations

This is the solution to the problem posed last episode.

It creates an association between the profiles we're collecting stats for and the stats we've collected so that they can access each other.

Back to index


Loading up those records got a little bit messy, the part I missed was how to insert a stat with the profile_id, so they are correctly associated in the db? I'm creating a seeds.exs file with some basic seed data that has a has_many belongs_to relationship and would like some help to understand that better.

Also, should I have a not null constraint on profile_id in the stats table? eg:

add: profile_id, references(:profiles, on_delete: :nothing), null: false

so no orphan stats can be inserted?

- camstuart · 2 years ago

There are a number of ways to do it, but all you need for the association on the db level is to write the correct profile_id. Make sure your changeset includes profile_id since it doesn't when generated!

A null constraint would make perfect sense here, and I believe I added one later in the series.

- alchemist · 2 years ago


- camstuart · 2 years ago

Hi, I'm new to Elixir. Is there a way, I can get the object an association belongs to without writing a query and without its id. For example, is a stats belongs to a particular profile. could I access the profile it belongs to? I need to create a custom validation that involves checking the other stats rows in the DB that belong to the same profile.

- takueg · 4 months ago

@takueg: Without a query sounds difficult! I may misunderstand what you mean, though. Could you elaborate a bit on what you're trying to do?

If you've already set up the association, you could access the parent struct with the dot syntax.

- alchemist · 4 months ago