2

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

Community
  • 1
  • 1
rwb
  • 4,309
  • 8
  • 36
  • 59
  • Can you show your other models too just so that the relationship between them is clear. – Aaditi Jain Dec 09 '14 at 17:57
  • Updated. Thanks for looking – rwb Dec 09 '14 at 18:14
  • I would question why you don't have to write any raw SQL. For your purposes `>=` operator, that is fully portable across rdbms's. It feels like trying to force yourself into the AREL box is just causing unnecessary headaches. – BBonifield Dec 09 '14 at 20:07

0 Answers0