我有两个关联,例如外科疾病和眼睛疾病。我想获得这两个主动关系的 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/