ruby-on-rails - 如何在 Rails 3 中使用 OR 条件合并两个事件记录关系并返回结果也是事件关系而不是数组?

标签 ruby-on-rails ruby ruby-on-rails-3 activerecord arel

我有两个关联,例如外科疾病和眼睛疾病。我想获得这两个主动关系的 Ored 结果。但是下面的代码给了我一个数组。

 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 一起使用。我目前使用的是 Rails 3.2,所以无法使用它。

我还看到这个功能将随带有 dhh 的rails5 commit 一起提供。 .但现在不知道如何用rail3解决这个问题。

我尽力理解我的问题。如果需要其他信息,请告诉我。 提前致谢!

最佳答案

您可能需要使用 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)  
}  

关于ruby-on-rails - 如何在 Rails 3 中使用 OR 条件合并两个事件记录关系并返回结果也是事件关系而不是数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34103032/

相关文章:

ruby-on-rails - 使用子文件夹中的 Controller 设计 UninitializedConstant ApplicationController

mysql - Ruby 脚本处理 SQL 文件中的每一行

mysql - 2 个 HTTP 请求同时检查记录是否存在,如果不存在则创建它 = 重复记录

ruby - 如何使用 ruby​​ 将\\u0026 转换为 &

ruby-on-rails - 在Rails查询中包含LIKE子句的最佳方法是什么?

ruby-on-rails - Rails - 推送到 Heroku 时出错 - 没有看到 Gemfile.lock

ruby-on-rails - Rails View 如何访问关注点?

ruby-on-rails - 使用accepts_nested_attributes_for时<Child's Parent>不能为空(Rails 4)

ruby-on-rails - ruby on rails 基础帮助

ruby-on-rails-3 - 在 Rails 3 上使用 Rspec 和 MongoID 清除或重置测试数据库