0

我正在尝试创建一种结合了其他三种关系的关系。前三个都是同一类,我想要一个企业集团,但是我找不到一个很好的“arel”方式。

这是我正在尝试做的一个例子。

有效的 SQL 查询是

SELECT `records`.* FROM `records` INNER JOIN `memberships` ON `records`.`subject_membership_id` = `memberships`.`id` OR `records`.`recorder_membership_id` = `memberships`.`id` OR `records`.`subject_membership_id` = `memberships`.`id` WHERE `memberships`.`group_id` = 4

当然,我想以铁路的方式做到这一点。这是我到目前为止所拥有的。它应该是不言自明的,所以我不会浪费你的时间进一步解释它。

class Group < ActiveRecord::Base
  has_many :recorded_records, :through => :memberships, :source => :recorded_records, :class_name => "Record"
  has_many :reported_records, :through => :memberships, :source => :reported_records, :class_name => "Record"
  has_many :reviewed_records, :through => :memberships, :source => :reviewed_records, :class_name => "Record"

  #has_many :records through recorded_records, reported_records, reviewed_records??
  # Psuedo code above... Wondering how best to do this. I've tried...
  def records
    recorded_records | reported_records | reviewed_records
  end

  # But that makes three seperate database queries when what I really want is...
  # SELECT `records`.* FROM `records` INNER JOIN `memberships` ON `records`.`subject_membership_id` = `memberships`.`id` OR `records`.`recorder_membership_id` = `memberships`.`id` OR `records`.`subject_membership_id` = `memberships`.`id` WHERE `memberships`.`group_id` = 4

end

你们真棒!谢谢 :)

4

2 回答 2

2

您可以使用自定义连接来做到这一点。使用上面的 SQL:

Record.joins('INNER JOIN `memberships` ON `records`.`subject_membership_id` = `memberships`.`id` OR `records`.`recorder_membership_id` = `memberships`.`id` OR `records`.`subject_membership_id` = `memberships`.`id` WHERE `memberships`.`group_id` = 4')

通过一些工作,您可以将其添加为模型中的方法,使其接受参数等。

这里的 Railsguide给出了一些使用示例.join

于 2013-02-22T13:08:02.620 回答
0

好的!嘿,非常感谢您的帮助,@RiPuk。你激发了我的一些想法。我所做的是从 select 语句中创建一个视图:

AS SELECT
  `records`.`id` AS `record_id`,
  `memberships`.`group_id` AS `group_id`
FROM (`records` join `memberships`) where ((`records`.`subject_membership_id` = `memberships`.`id`) or (`records`.`recorder_membership_id` = `memberships`.`id`) or (`records`.`subject_membership_id` = `memberships`.`id`));

我将此视图命名为view_group_records,然后创建了一个名为 GroupRecord 的 ActiveRecord 模型(具有适当的关系),现在在我的 Group 模型中,我建立了has_many与 GroupRecord 的关系,然后has_many :records, :through => :group_records.

这似乎效果很好!

但是您的解决方案绝对有效。

于 2013-02-22T20:49:25.013 回答