I have three models Threads, Events, Posts and I want to have each events to have one thread and each Posts to have one thread. Thread either belongs to events or posts.How to achieve this ?
The question is not very specific. I guess you are looking for some sort of constraint but as far as I know there is no such thing built into the language.
The whole thread belongs to a post or event sounds a bit backwards. Are you sure the don’t belong to a thread? (not that it really matters though)
Question is not clear. This seems more an SQL question. Also nothing to do with Phoenix, yet this is asked in the Phoenix forum.
I guess in the threads table you need to have 2 foreign keys where one may be null?
add :event_id, references(:events), null: true
add :post_id, references(:posts), null: true
And to add a DB constraint to ensure that at least one is not null:
create constraint(
:threads, :event_or_post_not_null, check:
"(NOT (event_id IS NULL AND post_id IS NULL))")
Sorry for not being clear. I was looking for something similar to Active Record Associations — Ruby on Rails Guides has_one through and upon extensive search I found out this Ecto.Schema – Ecto v2.2.6 (hexdocs.pm)
I have an example of has_many through but should be the same for has_one