Create composable query using table in another context

Hi, I’m trying to migrate this query into a composable one, Rnod is in the context of Analytic, and Fact in the registry context.

This query works ok

Repo.all(from r in Rnod, inner_join: f in Quant.Registry.Fact, where: f.id == r.fact_id)

But the composable one:

    Rnod 
        |> join(:inner, [r], f in assoc(f, :fact))
        |> Repo.all

Shows this error: unbound variable f in query.

What should be the way to execute this, in order to recognize the schema from another context.

missing something?

You probably meant to write f in assoc(r, :fact).

1 Like

@alco

I fixed the query, but now the error is this:

could not find associationfacton schema Quant.Analytic.Rnod

   Rnod 
       |> join(:inner, [r], f in assoc(r, :fact))
       |> Repo.all

What does your schema look like?

@alco

I think the main issue is because they are in different contexts?

defmodule Quant.Analytic.Rnod do
  use Ecto.Schema
  import Ecto.Changeset


  schema "rnods" do
    field :entry, :decimal
    field :entry_time, :time
    field :exit, :decimal
    field :exit_time, :time    
    field :notes, :string
    field :risk, :decimal
    field :best_entry_price, :decimal
    field :best_exit_price, :decimal
    field :vwap_at_entry, :decimal
    field :shares, :decimal    
    field :traded, :integer
    field :fact_id, :id
    field :direction_id, :id
    field :exit_reason_id, :id
    field :rnod_category_id, :id    
  end
end
defmodule Quant.Registry.Fact do
  use Ecto.Schema
  import Ecto.Changeset

  schema "facts" do
    field :atr, :decimal
    field :average_volume, :decimal
    field :candle_defining_level, :integer
    field :daily_volume, :decimal
    field :date, :date    
    field :high, :decimal
    field :institutional_ownership, :decimal    
    field :key_open_price, :decimal    
    field :low, :decimal
    field :open_price, :decimal
    field :retest, :integer
    field :premarket_populated, :integer
    field :shares_float, :decimal
    field :short_float, :decimal
    field :to_use_atr, :decimal
    field :video_url, :string
    field :second_day_play, :integer
    field :catalyst_note, :string
    field :candles_to_direction, :integer
    field :stock_id, :id
    field :stock_style_id, :id
    field :gap_id, :id
    field :gap_trend_id, :id
    field :first_direction_id, :id
    field :directional_simplicity_id, :id
    field :long_trend_id, :id
    field :catalyst_style_id, :id
    field :key_level_reference_id, :id
  end
end

In your Quant.Analytic.Rnod schema:
field :fact_id, :id
should be:
belongs_to :fact, Quant.Registry.Fact

1 Like

@mika It worked. Thanks @alco

But then the phx.gen.html is not creating the connections as it should be?