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 would be to create users_files
and posts_files
tables and use has_one :through
. However, this looks excessive.
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?
You cannot get away of not having the belongs_to because that's where the foreign key is defined. You have two alternatives:
Flip the relationship so both users and posts have an avatar_id and photo_id pointing to the files table
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With