【问题标题】:How to query a polymorphic associated relationship to return data from multiple tables - rails4如何查询多态关联关系以从多个表中返回数据 - rails4
【发布时间】:2016-09-20 14:10:16
【问题描述】:

我有一些通过多态关联连接的表...

我正在尝试找到一种方法来进行单个查询以从多个这些表中返回数据...

我的模型如下:

#profile.rb
class Profile < ActiveRecord::Base
  has_many :user_profiles, dependent: :destroy
  has_many :wizards, through: :user_profiles, source: :user, source_type: "Wizard"
end

#user_profile.rb
class UserProfile < ActiveRecord::Base
  belongs_to :user, polymorphic: true, dependent: :destroy
  belongs_to :profile
end

#wizard.rb
class Wizard < ActiveRecord::Base
  has_one :user_profile, as: :user, dependent: :destroy
  has_one :profile, through: :user_profile
  has_one :wizard_specialization, dependent: :destroy
  has_one :career, through: :wizard_specialization
end

#career.rb
class Career < ActiveRecord::Base
  has_many :wizard_specializations, dependent: :destroy
  has_many :wizards, through: :wizard_specializations
end

我如何编写一个联接(或 :includes)查询来返回 所有 向导的配置文件,以及他们来自 profiles 表的信息,还包括他们从careers 表通过wizard_specializations?

提前致谢。

PS:如果我可以排除 created_atupdated_at 之类的字段,那就太好了

【问题讨论】:

    标签: ruby postgresql activerecord polymorphic-associations ruby-on-rails-4.2


    【解决方案1】:

    您可以使用 ActiveRecord 的includes 方法来处理eager-load associated data。将其与 select 方法结合起来,仅包含或排除您想要的列:

    Wizard.includes(:career, :profile).select('wizards.name', 'wizards.etc', 'careers.name', 'careers.etc', 'profiles.*')
    

    【讨论】:

    • 感谢您的回复...如何将profiles 表中的数据也包含在内?
    • 我可以加载类似这样的内容:Wizard.includes(wizard_specialization: :career, user_profile: :profile),但除了wizards 表之外,我无法从任何其他表中选择任何内容。
    • 你应该可以做到Wizard.includes(:career, :profile)。我认为 ActiveRecord 将自动遍历 through 依赖项并包含该向导的配置文件。
    • 仅供参考,这是一个 SO 问题,解释了如何排除某些列,这比写出包含列的列表更容易:stackoverflow.com/questions/17431028/…
    • 是的,我可以这样做...但是当我尝试选择时出现问题...所以.select('wizards.id, wizards.name'... 有效...但是当我尝试从career 中进行选择时它会中断或profile
    【解决方案2】:

    我不确定 Rails 是否支持使用我的所有设置配置进行直接 AR 查询...

    无论如何,我最终决定用纯 SQL 编写它并在以下方面的帮助下执行:

    ActiveRecord::Base.connection.execute(query)
    

    query 包含我的纯 SQL 语句,其中包含 SELECTs 和 JOINs 和 WHEREs

    【讨论】:

      猜你喜欢
      • 2016-06-04
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-20
      • 2020-07-31
      相关资源
      最近更新 更多