# Polymorphic associations ecto

**URL:** <https://forum.elixirforum.com/t/polymorphic-associations-ecto/38780>\
**Category:** Questions\
**Tags:** ecto, associations\
**Created:** [April 7, 2021, 6:57am UTC](https://forum.elixirforum.com/t/polymorphic-associations-ecto/38780 "2021-04-07T06:57:19Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![romaluca](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/romaluca/32/11213_2.png) [@romaluca](https://forum.elixirforum.com/u/romaluca)\
**Post date:** [April 7, 2021, 6:57am UTC](https://forum.elixirforum.com/t/polymorphic-associations-ecto/38780/1 "2021-04-07T06:57:19Z")

</div>

Hi i have a table “activities” in my db with colums: id, user\_id, user\_to\_id, photo\_id, type  
type can be: ‘vote’, ‘user\_follow’, ‘photo\_follow’

I created a schema Vote, UserFollow, PhotoFollow.  
The schema of Vote is like this:

```elixir
defmodule Shuttertop.Votes.Vote do
  @moduledoc false

  use TypedEctoSchema
  import Ecto.Changeset

  require Shuttertop.Constants

  alias Shuttertop.Accounts.User
  alias Shuttertop.Constants, as: Const
  alias Shuttertop.Photos.Photo

  typed_schema "activities" do
    field(:type, :integer, default: Const.action_vote)
    belongs_to(:photo, Photo)
    belongs_to(:user, User)

    timestamps()
  end
...

```

The Photo schema is like this:

```elixir
defmodule Shuttertop.Photos.Photo do
  @moduledoc false

  use TypedEctoSchema
  import Ecto.Changeset

  alias Shuttertop.Accounts.User
  alias Shuttertop.Votes.Vote

  typed_schema "photos" do
    field(:name, :string, null: true)
    field(:slug, :string, null: false)
    has_many(:votes, Vote, on_delete: :delete_all)
...

```

when i do a select like:

```elixir
from(
          p in Photo,
          preload: [:user, :votes]
        )

```

the rows in photo.votes contains also PhotoFollow type

How can i get only Vote type without specify it in filter?

Now i can do it with this code, but i don’t like it:

```elixir
from(
          p in Photo,
          distinct: true,
          left_join: v in Vote,
          on: [photo_id: p.id, type: ^Const.action_vote],
          preload: [:user, votes: v]
        )

```

Thanks

---

<div class="post-metadata">

**Author:** ![al2o3cr](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/al2o3cr/32/3457_2.png) [@al2o3cr](https://forum.elixirforum.com/u/al2o3cr)\
**Post date:** [April 7, 2021, 11:59am UTC](https://forum.elixirforum.com/t/polymorphic-associations-ecto/38780/2 "2021-04-07T11:59:39Z")

</div>

Adding a [`where:`](https://hexdocs.pm/ecto/Ecto.Schema.html#has_many/3-filtering-associations) to your `has_many :votes` should do what you’re looking for.
