Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
861 views
in Technique[技术] by (71.8m points)

sql - 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...