Ruby on Rails:创建一个结合了三个其他关系的关系

时间:2013-02-22 12:58:43

标签: ruby-on-rails relational-database rails-activerecord

我正在尝试创建一个结合了其他三种关系的关系。最初的三个都是同一个类,我喜欢像一个集团,但是我找不到一个很好的“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

当然,我想做那种rails方式。这是我到目前为止所拥有的。它应该是非常自我解释的,所以我不会浪费你的时间进一步解释它。

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

你们摇滚!谢谢:))

2 个答案:

答案 0 :(得分: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 here提供了一些使用.join

的示例

答案 1 :(得分: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模型中,我与GroupRecord建立了has_many关系,然后{has_many :records, :through => :group_records 1}}。

这似乎运作良好!

但你的解决方案绝对有效。