FaridAP
FaridAP

Reputation: 23

Rails query - How to joins two tables on specific columns

I have a model(OwnershipTransfer) with two columns that are belongs_to to another model(Account):

  class OwnershipTransfer < ApplicationRecord

   belongs_to :transfer_from, class_name: 'Account'
   belongs_to :transfer_to, class_name: 'Account'

  end
class Account < ApplicationRecord

has_many :ownership_transfers, class_name: 'OwnershipTransfer', foreign_key: :transfer_to

end

I am trying to join Account and OwnershipTransfer with a SQL like this

SELECT * FROM petalmd_development.accounts a 
join petalmd_development.ownership_transfers ot 
on a.id = ot.transfer_from_id 
where ot.meeting_event_id = 458

I have tried: Account.joins(:ownership_transfer).on(Account.arel_table[:id].eq(OwnershipTransfer.arel_table[:transfer_from_id])).where(ownership_trasnfers: {meeting_event_id: 458})

But Delegating on to arel is deprecated in rails 6 any clue to explicitly select a column to JOIN ON?

Upvotes: 2

Views: 2238

Answers (1)

dbugger
dbugger

Reputation: 16389

Breaking the parts out for clarity.

The tables involved...

account_table = Account.arel_table
transfership_table = OwnershipTransfer.arel_table

The arel join...

join = account_table.join(transfership_table).on(account_table[id].eq( transfership_table[:transfer_from_id] ))

Using the arel join in the query...

Account.joins(join.join_sources).where(ownership_transfers: {meeting_event_id: 458})

Upvotes: 3

Related Questions