elt547

elt547

Can I fake a polymorphic association with a virtual schema field?

So I’ve opted for the “easy method” of polymorphic associations, where you have a column for each possible polymorphic type. That’s the database implementation, but now I’m wondering what to do on the schema implementation.

The table looks something like this:

Table inbox_items {
  id int [pk]
  profile_id int [ref: <> profiles.id]
  
  post_id int [ref: < posts.id]
  poll_id int [ref: < posts.id]
  comment_id int [ref: < comments.id]
}

Is there a way for me to add a virtual field to the schema so that I can cast to and from the correct column? That way I could just create it like %InboxItem{association: %Post{}} and it would know to save the id to the post_id column. Similarly can I make it able to respond to something like Repo.preload(inbox_item, :association) so I can fill the virtual field when loading?

Most Liked

elt547

elt547

Yeah, it’s the first method shown in the guide. It’s really just one workaround or another, because the polymorphic association is what I need more or less. Do you have any alternative suggestions? I tried the many-to-many method and it was a nightmare, and the guides are remarkably incomplete on the subject.

I read a few blog posts but they all recommended against the more complex approaches. I had implemented the many-to-many and it was awful, and I considered table inheritance in postgres but was advised against it.

Actually almost my entire domain has these kinds of relationships. I really shouldn’t be using a relational db but I really wanted to use elixir, and I have limited graph db experience so I don’t want to deal with more learning since I’m on a time crunch to get my mvp shipped.

MRdotB

MRdotB

What about exclusive belongs to. You make your inbox_items hold fk for all your other models

MRdotB

MRdotB

# you want to left_join and preload the fields
query =
  from(
    item in InboxItem,
    left_join: post in assoc(item, :post),
    left_join: poll in assoc(item, :poll),
    left_join: comment in assoc(item, :comment),
    preload: [
      post: post,
      poll: poll,
      comment:comment 
    ]
  )

items = Repo.all(query, opts)

# I don't think it will be possible to set the virtual_field in the ecto query
# You can do something like below to set it but I think this part should be done
# in the view
Enum.map(items, fn item ->
  model =
    cond do
      is_binary(item.post_id) ->
        item.post

      is_binary(item.poll_id) ->
        item.comment

      is_binary(item.comment_id) ->
        item.comment
    end
   # add the model to the virtual field manually
  %{item | virtual_field: model}
end)

Where Next?

Popular in Questions Top

gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
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 have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
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 ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New

We're in Beta

About us Mission Statement