简体   繁体   English

如何在 Ruby on Rails 中进行无外键连接?

[英]How to make a Join without foreign-keys in Ruby on Rails?

I am working with a very old Salesforce database, and need to make a query with a join without foreign keys using ActiveModels in Ruby on rails.我正在使用一个非常旧的 Salesforce 数据库,并且需要在轨道上使用 Ruby 中的 ActiveModels 使用没有外键的连接进行查询。

The app is modeling the salesforce into ActiveModels like this:该应用程序将 salesforce 建模为 ActiveModel,如下所示:

module Sf
  class Service < Sf::BaseRecord
    OBJECT_NAME = 'service__c'
    self.table_name = "salesforce.#{OBJECT_NAME}"
    self.primary_key = 'sfid'

    has_many :state_services, foreign_key: :service_id__c, dependent: nil

  end
end

I have a huge query that I need to write using ActiveModel.我有一个庞大的查询需要使用 ActiveModel 编写。

salesforce.contentversion c 
JOIN salesforce.program__c pc 
JOIN salesforce.service__c sc 
    ON pc.legal_service_id__c = sc.sfid

I have Program and Service created.我创建了程序和服务。 legal_service_id__c is not a key but sfid is. legal_service_id__c 不是密钥,但 sfid 是。

How should I model this JOIN relationship into my models as the columns needed to the JOINs are not keys from each other?我应该如何 model 这个 JOIN 关系到我的模型中,因为 JOIN 所需的列不是彼此的键?

There are multiple ways of going about this有多种方法可以解决这个问题

  1. Write the SQL query in string将 SQL 查询写入字符串
sql = "Select * from ... your sql query here"
records_array = ActiveRecord::Base.connection.execute(sql)
  1. Pass the JOIN clause as the string when using a join Eg.使用连接时将 JOIN 子句作为字符串传递。 ContentVersion.all.joins("JOIN program__c pc ON pc.legal_service_id__c = content_versions.sfid")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM