tadasajon

tadasajon

Should I add belongs_to to my schema? What do I gain?

I have added users to my Phoenix application through phx.gen.auth and I have the following schema defined in lib/myapp/accounts/user.ex:

  schema "users" do
    field :email, :string
    field :password, :string, virtual: true, redact: true
    field :hashed_password, :string, redact: true
    field :confirmed_at, :naive_datetime

    timestamps()
  end

Now I’m expanding my app and adding a catalog of products – and I want to make sure that each product has a maker in my system, which should correspond to a user from the accounts context. So I ran the following Phoenix generator:

mix phx.gen.html Catalog Product products url:string:unique product:map maker_id:references:users

This is the migration that was generated:

def change do
  create table(:products) do
    add :url, :string
    add :product, :map
    add :maker_id, references(:users, on_delete: :nothing)

    timestamps()
  end

  create unique_index(:products, [:url])
  create index(:products, [:maker_id])
end

and this was the schema that was generated in lib/myapp/catalog/product.ex:

schema "products" do
  field :product, :map
  field :url, :string
  field :maker_id, :id

  timestamps()
end

I wanted to make sure I could not add a product to my system without associating it with a user, and that deleting a user would delete all their associated products, so I adjusted the migration to add null: false and on_delete: :delete_all to the maker_id.

    add :maker_id, references(:users, on_delete: :delete_all), null: false

So I should now have a solid foreign key for every product that will point to the users table.

Here are a few questions I have:

  1. Why didn’t the generator automatically add a belongs_to macro to my products schema? It should know that the maker_id is a foreign key pointing to users, so it ought to have known how to do this.

  2. How will my app benefit if I adjust the products schema by adding the belongs_to macro? The relationship is already constrained in Postgres, after all.

  3. Do I need to add a corresponding has_many macro to my users schema? What do I lose if I don’t?

  4. Is this the correct way to specify belongs_to for the situation I have described:

schema "products" do
  field :product, :map
  field :url, :string
  belongs_to :user, Myapp.Accounts.User, foreign_key: :maker_id

  timestamps()
end
  1. Should I set the :source option, which is mentioned in the docs? Ecto.Schema — Ecto v3.14.0

Thanks!

Most Liked

dimitarvp

dimitarvp

I can’t answer all your questions well so I’ll respond to the title and a part of them:

Add those macros only if you need a back-reference to the owning object in your code, and if the owning object needs to know all the object it owns / points to. In the past I’ve commented out various belongs_to and has_many statements if after analysis I found I don’t use them.

However, with time I preferred to leave them in because they are not introducing a noticeable load on the DB and their presence serves as good DB design documentation.

50/50, nowadays I lean to leaving them in even if I don’t use them but I can see why people would comment them out (or skip them altogether) as well.

christhekeele

christhekeele

I often find myself using belongs_to back refs during debug console sessions, so I like to leave them around since it impacts little else.

Where Next?

Popular in Questions Top

Tee
can someone please explain to me how Enum.reduce works with maps
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
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
vac
Hi, I’m quite new in Elixir and I’m trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and I...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29603 241
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
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
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement