如何在 rails 3 和 return 中将两个活动记录关系与 OR 条件合并,结果也是一个活动关系而不是数组?

How can I merge two active record relation with OR condition in rails 3 and return result also an active relation not array?

我有两个关联,例如 surgical_diseases 和 eye_disease.I 想要获得两个活动的 Ored 结果 relation.But 下面的代码给了我一个数组。

 has_many :surgical_diseases
 has_many :eye_disease

 scope :all_disease ->(name) { joins(:surgical_diseases).where('surgical_diseases.name IN (?)') | joins(:eye_disease).where('eye_disease.name IN (?)') }

我看过 active-record-union gem 但这只适用于 active-record 4.I 我目前使用 rails 3.2 所以不能使用它。

我还看到此功能将随 rails5 和 dhh 的 commit 一起提供。但不确定我现在如何使用 rail3 解决此问题。

我尽力理解我的 question.Please 如果需要任何其他信息,请告诉我。 提前致谢!

或许,左外连接可以帮到你:

scope :all_disease ->(name) { 
  joins('LEFT OUTER JOIN surgical_diseases ON surgical_diseases.whatever_table_for_your_models_id = whatever_table_for_your_models.id')
  .joins('LEFT OUTER JOIN eye_diseases ON eye_diseases.whatever_table_for_your_models_id = .whatever_table_for_your_models.id')
  .where('surgical_diseases.name IN (?) OR eye_diseases.name IN (?)', name)

您可能需要使用 find_by_sql 获取 ID,然后找到这些 ID 以获得 ActiveRecord::Relation。

scope :all_disease ->(name) {  
  ids = YourTable.find_by_sql <<-SQL  
    SELECT your_table.id FROM your_table INNER JOIN surgical_diseases sd ON   sd.your_table_id=your_table.id WHERE sd.name IN (#{name})  
    UNION  
    SELECT your_table.id FROM your_table INNER JOIN eye_diseases ed ON ed.your_table_id=your_table.id WHERE ed.name IN (#{name})  
  SQL  

YourTable.where(id: ids)  
}