Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

has_one without belongs_to in ecto/phoenix/elixir

Problem

I have a files table and there are many other tables that create a one-to-one association, e.g. users might have a avatar and posts might have photo.

A possible solution

A possible solution would be to create users_files and posts_files tables and use has_one :through. However, this looks excessive.

The ideal solution

The ideal solution would be to define tables like this

users
 - avatar_id

posts
 - photo_id

and have with: parameter in has_one so the schema looks like this

schema "users" do
    has_one :avatar, MyApp.FileDb, with: :avatar_id, foreign_key: :id #id is default

end

schema "posts" do
    has_one :photo, MyApp.FileDb, with: :photo_id, foreign_key: :id

end

and that way you don't need to define a belongs_to on files. Is there a similar mechanism already? What is the standard way to deal with this in Phoenix?

like image 427
Cristian Garcia Avatar asked Sep 19 '15 15:09

Cristian Garcia


1 Answers

You cannot get away of not having the belongs_to because that's where the foreign key is defined. You have two alternatives:

  1. Flip the relationship so both users and posts have an avatar_id and photo_id pointing to the files table

  2. Define both "users_files" and "posts_files" tables without a "files" table. "users_files" and "posts_files" will have the complete table structure which can be shared at the model level in Ecto. We actually talk about this case in Ecto docs: http://hexdocs.pm/ecto/Ecto.Schema.html#belongs_to/3 (see the polymorphic section)

like image 127
José Valim Avatar answered Nov 01 '22 19:11

José Valim