ActiveRecord / Arel: How to query self joined table (from has_many relation)?

480 Views Asked by At

I'm trying to convert some code from Squeel to ActiveRecord / Arel. The models looks like this:

class Contract < ActiveRecord::Base
  belongs_to :institution
  belongs_to :issuer

  has_many :related_contracts, :through => :issuer, :source => :contracts
end

class Institution < ActiveRecord:Base
  has_one :contract, :dependent => :destroy
end

class Issuer < ActiveRecord:Base
  has_many :contracts, :dependent => :destroy
end

And the code i am trying to rewrite, in Contract:

def self.foo
  joins {[institution, issuer.institution]}
  .where { |db| db.last_date >= db.related_contracts.last_date }
end

I can convert the joins and >= operator inside the where query using ActiveRecord and Arel respectively. However, I do not know how I can reference the equivalent of db.related_contracts using either of the two syntaxes (since i can't call arel_table on RelatedContract as it isn't a class).

EDIT: This is the closest i have so far:

  def self.foo
    fc = Contract.arel_table
    rc = Arel::Table.new(:related_contracts)
    joins(:institution, :related_contracts => :institution)
    .where(fc[:last_date].gteq(rc[:last_date]))
  end

But the where condition is using [related_contracts].[last_date] instead of [related_contracts_contracts].[last_date]

Does anyone have any ideas? I really do not want to resort to writing raw SQL strings. I think these are related: How to get the arel table of a habtm association? Convert ActiveRecord habtm query to Arel

Using Rails 3.2.12

Thanks

0

There are 0 best solutions below