Filter `has_many` using local schema field

Hi everyone,

I’m struggling to setup filtering of a has_many association that depends on the local schema’s field. By local schema, I mean the schema in which the has_many is defined.


I’ve simplified my problem into the following example:

Let’s say I have a Playlist and Song schema. A Playlist has many Songs, and an :current_position field. A Song belongs to a Playlist, so it carries the :playlist_id, :playlist_position and song metadata.

I would like to have a has_many association for Songs whose :playlist_position >= playlist.current_position. I’d like to also have another association that would cover the remaining songs.

How do I accomplish this?


Here are the following example schemas:

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id
  schema "playlists" do
    field :name, :string

    field :current_position, :integer, default: -1

    # should be filtering for `song.playlist_position >= :current_position
    has_many :queued_songs, Song `

    # should be filtering for `song.playlist_position < :current_position`
    has_many :played_songs, Song 

    timestamps()
  end

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id
  schema "playlist_songs" do
    field :playlist_position, :integer
    # other fields

    belongs_to :playlist, Playlist

    timestamps()
  end

I’m not sure comparisons like that are supported but they should be with the where: {:fragment, expr} option. I’d read through this whole section first.