【问题标题】:Rails 4 scope joins to find either/or relationshipsRails 4 范围连接以查找非此即彼的关系
【发布时间】:2018-05-10 11:01:35
【问题描述】:

我有一个带有多个关系的 rails 4.2.8 应用程序。我的交互模型具有并属于许多基因(具体而言,一个交互可以有 2 个基因,而一个基因可以属于任意数量的交互),而基因模型又具有许多药物和疾病。

我试图让用户根据其中一个或另一个基因是否具有与之相关的药物和/或疾病来过滤交互。如果选择了药物或疾病“过滤器”,则下面的代码将按要求工作,因为显示与至少一个基因的所有相互作用以及这些关联中的至少一个。

但是,当检查两个过滤器时,我只显示其中一个或两个基因具有至少一种药物至少与一种疾病相关的相互作用。我还想展示一个基因有药物但没有疾病和另一个基因有疾病但没有药物相关的相互作用。

模型

class Interaction < ActiveRecord::Base
    has_and_belongs_to_many :genes
    ...

    scope :disease_associated, -> { joins(genes: :diseases) }
    scope :drug_target, -> { joins(genes: :drugs) }
    ...
end

class Gene < ActiveRecord::Base
    has_and_belongs_to_many :interactions
    has_and_belongs_to_many :drugs
    ...
end

class Drug < ActiveRecord::Base
    has_and_belongs_to_many :genes
end

class Disease < ActiveRecord::Base
    has_and_belongs_to_many :genes
end

交互控制器

class InteractionsController < ApplicationController
    ...
    @interactions = @interactions.disease_associated() if params[:filter_disease].present?
    @interactions = @interactions.drug_target() if params[:filter_druggable].present?
    ...

我没有找到任何明显解决这个问题的方法/问题,尽管这可能是因为我无法找到足够简洁的词来解决这个问题以进行有效搜索。

提前致谢!

【问题讨论】:

    标签: ruby-on-rails named-scope


    【解决方案1】:

    在 Rails 4 中,我可以提出两种选择:

    1。身份证列表

    ids = []
    ids |= Interaction.disease_associated.pluck(:id) if params[:filter_disease].present?
    ids |= Interaction.drug_target.pluck(:id) if params[:filter_druggable].present?
    
    interactions = Interaction.where(id: ids)
    

    清晰,但如果数据库中有很多交互则不好。

    2。联合

    Gem active_record_union gem 为 Rails 提供 SQL UNION 支持。

    interactions = Interaction.none
    interactions = interactions.union(Interaction.disease_associated) if params[:filter_disease].present?
    interactions = interactions.union(Interaction.drug_target) if params[:filter_druggable].present?
    

    附:常见建议:通过常见查询而不是域来设计您的数据库。

    【讨论】:

      猜你喜欢
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 2014-08-26
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多